Game Movement

elective course


By taking advantage of the new way to draw components explained in the game rotation chapter, the action is now more flexible.

play again how to move the object? in speed component

an attribute in the constructor newPos() attribute, which represents the current speed of the component. speed methods are modified to angle methods. And

By default, the component faces upwards, and the position of the component is calculated by speed attribute set to 1, the component will start to move forward.

Example

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

turning

we also hope to be able to turn left and right. Create a named moveAngle the new attribute, indicating the current movement value or rotation angle. In newPos() in the method according to moveAngle attribute calculation angle:

Example

Set the moveangle attribute to 1 and see what happens:

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

Using the keyboard

How does the red block move when using the keyboard? When you use the 'up' arrow, the red block does not move up and down, but moves from one side to the other and moves forward, and rotates left and right when pressing the left and right arrow keys.

Example

Try It Yourself

Make sure the game area is focused, then use the arrow keys to move the red block.