tmlib.js handson
ゲームを作ろう♪
phi
自己紹介
- 名前 ... phi(ファイ)
- 言語 ... C/C++, Python, JavaScript
- 年齢 ... 24 歳
- 仕事 ... 某ソーシャルゲーム会社で働いています
- Twitter ... @phi_jp
- Blog ... TM Life
- 参考書の執筆
- enchant.js開発のレシピ
- enchant.js スマートフォンゲーム開発講座
避けゲーを作ろう
今回はシンプルなゲームを作って
基本的なゲームプログラミングの流れを学びます.
作るゲームはこちら
クリック or タッチで敵を避け続けるゲームです.
コードを fork しよう
作ったコードをfork します.

定数とグローバル変数を追加
画面幅を定数に, app をグローバル変数にします.
/* * 定数 */ var SCREEN_WIDTH = 465; var SCREEN_HEIGHT = 465; var SCREEN_CENTER_X = SCREEN_WIDTH/2; var SCREEN_CENTER_Y = SCREEN_HEIGHT/2; /* * グローバル変数 */ var app = null; tm.main(function() { app = tm.app.CanvasApp("#world"); app.resize(SCREEN_WIDTH, SCREEN_HEIGHT); app.fitWindow(); app.background = "rgba(0, 0, 0, 0.1)";
プレイヤークラスを定義
プレイヤークラスを定義します.
あと定数にPLAYER_SIZE(32くらい)を追加
/* * プレイヤー */ var Player = tm.createClass({ superClass: tm.app.TriangleShape, // 初期化 init: function() { this.superInit(PLAYER_SIZE, PLAYER_SIZE); }, // 更新 update: function(app) { var p = app.pointing; // マウスダウン or タッチ判定 if (p.getPointing()) { // 移動 this.x += app.pointing.deltaPosition.x*1.25; // 画面内制御 if (this.x < 0) { this.x = 0; } else if (this.x > SCREEN_WIDTH) { this.x = SCREEN_WIDTH; } } } });
プレイヤーを生成, 表示
メイン処理でプレイヤーを生成,シーンに追加する
tm.main(function() {
app = tm.app.CanvasApp("#world");
app.resize(SCREEN_WIDTH, SCREEN_HEIGHT);
app.fitWindow();
app.background = "rgba(0, 0, 0, 0.1)";
// プレイヤー
var player = Player();
app.currentScene.addChild(player);
player.x = SCREEN_CENTER_X;
player.y = SCREEN_HEIGHT-100;
app.currentScene.update = function() {
};
app.run();
});実行結果
下図のように三角形のプレイヤーが表示されればGood!

マウスをクリックして動かすとプレイヤーが
動くのがわかると思います.
エネミークラスを定義
プレイヤークラスをコピペして少し修正
/* * エネミー */ var Enemy = tm.createClass({ superClass: tm.app.StarShape, // 初期化 init: function() { this.superInit(PLAYER_SIZE, PLAYER_SIZE); }, // 更新 update: function(app) { this.y += 8; // 移動 this.rotation += 15; // 回転 // 削除判定 if (this.y > SCREEN_HEIGHT) { this.remove(); enemyList.erase(this); } } });
エネミークラスを生成, 表示
グローバル変数に enemyList を追加
/*
* グローバル変数
*/
var app = null;
var enemyList = null;
main 関数内の update 処理で
エネミーを生成, シーンに追加する
// エネミーリスト
enemyList = [];
// 更新
app.currentScene.update = function(app) {
// エネミー生成
if (app.frame % 8 == 0) {
// エネミー
var enemy = Enemy();
enemy.x = tm.util.Random.randint(0, SCREEN_WIDTH);
enemy.y = -50;
app.currentScene.addChild(enemy); // シーンに追加
enemyList.push(enemy); // リストに追加
}
}
実行結果
星の形をしたエネミーが表示されれば Great!

あとは衝突判定だけ♪
プレイヤーとエネミーの衝突判定
下記のコードを main 関数の更新処理内に追加します.
// 更新
app.currentScene.update = function(app) {
// エネミー生成
...省略...
// プレイヤー, エネミー衝突判定
for (var i=0,len=enemyList.length; i<len; ++i) {
var enemy = enemyList[i];
// 衝突判定
if (player.isHitElement(enemy)) {
// Game Over
alert("game over! score: {0}".format(app.frame));
app.stop();
}
}
}実行確認
衝突したら下図のようにスコアが alert 表示されれば
Excellent!!!

これで完成♪
タイトルを設定
タイトルに『避けゲー - tmlib.js #techbuzz』を設定

Finish ボタンを押して編集完了♪
完成!!

スマートフォンで遊ぶも良し,
URL を送りつけて友達に自慢するも良し.
ありがとうございます
tmlibjs_handson
By phi
tmlibjs_handson
- 4,071