JavaScript»ゲーム制作»更新メソッド キャラクターにupdateとrenderメソッドをつくる
ファイル名: js-game/quest_00721.html
下のプログラムは、ガイコツの
ソースコード
class Hone {
constructor(image, x, y) {
this.image = image;
this.x = x;
this.y = y;
this.frame = 0;
this.tick = 0;
}
// がいこつオブジェクトの状態を更新するメソッド
// 毎フレーム位置をうごかし
// 10フレームに1回、画像を切り替える
update() {
this.tick++;
this.x += Math.floor(Math.random() * 3) - 1;
this.y += Math.floor(Math.random() * 3) - 1;
if (this.tick % 10 === 0) {
this.frame = ++this.frame % 3;
}
}
// がいこつオブジェクトをキャンバスに表示するメソッド
render(context) {
context.drawImage(this.image, this.frame * 32, 0, 32, 32, this.x, this.y, 32, 32);
}
}
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
const image = new Image();
image.src = "hone.png";
image.addEventListener("load", () => {
const hone = new Hone(image, 144, 144);
const FPS = 20;
const frameTime = 1 / FPS;
let prevTimestamp = 0;
const update = (timestamp) => {
const elapsed = (timestamp - prevTimestamp) / 1000;
if (elapsed <= frameTime) {
requestAnimationFrame(update);
return;
}
prevTimestamp = timestamp;
hone.update();
context.clearRect(0, 0, 320, 320);
hone.render(context);
requestAnimationFrame(update);
};
update();
});
解説
動き自体は「フレームレート(FPS)を設定する」と同じで、クラスとメソッドを使って書き替えたものです。Honeクラスにupdateとrenderメソッドを作っておき、関数update内で実行しています。
クラスとメソッドについては「クロネコをたくさん表示する(クラス使用)」と「メソッドでバブルを操作する」で解説しています。