Build Game Docs
10. Scene と GameObject を組み合わせる流れ
ここまでの関数を実際にどう並べてゲームを作り始めるかを、最小構成の流れとして整理します。create.js の関数詳細には踏み込まず、base.js の API をどう使うかに集中します。
手順 1. GameObject を継承して役割を作る
まず、プレイヤー、敵、弾、背景、UI などの役割ごとに GameObject を継承したクラスを作ります。初期化は spawn()、毎フレームの処理は update(dt)、見た目は draw(ctx) に分けるのが基本です。
class Player extends GameObject {
spawn() {
this.tags = "player";
this.hitType = "circle";
this.radius = 12;
}
update(dt) {
super.update(dt);
}
draw(ctx) {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fill();
super.draw(ctx);
}
}
手順 2. Scene を作って共有変数を用意する
次に new Scene() で舞台を作り、必要なら scene.vars にスコアや残り時間のような共有値を入れます。
const mainScene = new Scene();
mainScene.vars.score = 0;
mainScene.vars.phaseName = "Opening";
手順 3. add() で登場人物を並べる
作ったオブジェクトを add() で Scene に入れます。背景、敵、プレイヤー、UI の順に置くと、初期の見た目も把握しやすいです。
mainScene.add(new Background());
mainScene.add(new Enemy(420, 200));
mainScene.add(new Player(80, 200));
mainScene.add(new Hud());
手順 4. Game.init() と Game.setScene() で動かす
最後に Canvas を初期化して、今作った Scene を現在の場面として設定します。これでループが動き始め、Scene 内のオブジェクトが自動で処理されます。
Game.init("gameCanvas", true, {
width: 600,
height: 400
});
Game.setScene(mainScene);
このページ環境では、create.js を編集して再実行することで、同じ流れを何度でも試せます。