游戏运动
通过利用游戏旋转章节中讲解的绘制组件的新方式,动作现在更加灵活了。
如何移动物体?
在 component 构造函数中添加一个 speed 属性,该属性代表组件当前的速度。
还要对 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);
}
}
转弯
我们还希望能够左转和右转。创建一个名为 moveAngle 的新属性,它指示当前的移动值或旋转角度。在 newPos() 方法中根据 moveAngle 属性计算 angle:
实例
请将 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);
}
}
使用键盘
使用键盘时红色方块如何移动?当您使用“向上”箭头时,红色方块不会向上和向下,而是会从一侧移动到另一侧向前移动,并且会在按向左和向右箭头时左右旋转。
实例
确保游戏区域获得焦点,然后使用箭头键移动红色方块。