游戏动作
With the new way of drawing components, explained in the Game Rotation chapter, the movements are more flexible.
How to Move Objects?
Add a speed
property to the component
constructor, which represents the current speed of the component.
Also make some changes in the newPos()
method, to calculate the position of the component, based on speed
and angle
.
By default, the components are facing up, and by setting the speed property to 1, the component will start moving forward.
例子
function component(width, height, color, x, y) {
this.gamearea = gamearea;
这个.宽度=宽度;
这个.高度=高度;
this.angle = 0;
this.speed = 1;
这个.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);
}
}
亲自尝试 »
Making Turns
We also want to be able to make left and right turns. Make a new property called moveAngle
, which indicates the current moving value, or rotation angle. In the newPos()
method calculate the angle
based on the moveAngle
property:
例子
Set the moveangle property to 1, and see what happens:
function component(width, height, color, x, y) {
this.width = width;
这个.高度=高度;
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.填充样式 = 颜色;
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);
}
}
亲自尝试 »
Use the Keyboard
How does the red square move when using the keyboard? Instead of moving up and down, and from side to side, the red square moves forward when you use the "up" arrow, and turns left and right when pressing the left and right arrows.