Game 回転の章で説明しているように、コンポーネントを描画する新しい方法により、動きはより柔軟になりました。
コンポーネントの現在の速度を表す speed
プロパティを
component
コンストラクタに追加します。
また、newPos()
メソッドを多少変更して、speed
と
angle
基づき、コンポーネントの位置を計算します。
デフォルトでは、コンポーネントは上向きで、speed プロパティを 1 に設定すればコンポーネントは前進します。
function component(width, height, color, x, y) {
this.gamearea = gamearea;
this.width = width;
this.height = height;
this.angle = 0;
this.speed = 1;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.fillStyle = color;
ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
ctx.restore();
}
this.newPos = function() {
this.x += this.speed * Math.sin(this.angle);
this.y -= this.speed * Math.cos(this.angle);
}
}
Try it Yourself »
また、左右に向きを変えられるようにしようと思います。moveAngle
という新しいプロパティを作成します。
これは、現在の moving value(?)または回転角度を示します。newPos()
メソッドでは、
moveAngle
プロパティに基づいて角度を計算します:
moveangle プロパティを 1 に設定すると何が起こるかを確認します:
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.angle = 0;
this.moveAngle = 1;
this.speed = 1;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.fillStyle = color;
ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
ctx.restore();
}
this.newPos = function() {
this.angle += this.moveAngle * Math.PI / 180;
this.x += this.speed * Math.sin(this.angle);
this.y -= this.speed * Math.cos(this.angle);
}
}
Try it Yourself »
キーボードを使用すると、赤い四角はどのように動くでしょうか?赤い四角は、上下左右に移動する代わりに、「上向き」矢印を使用すると前方に移動し、 左右の矢印を押すと左右に回転します。