Game Movement

By using the new drawing component method explained in the game rotation chapter, the action is now more flexible.


How to move objects?

in component Add a speed attribute, which represents the current speed of the component.

also need to modify newPos() methods to make some changes based on speed and angle to calculate the component's position.

By default, the component is facing up, by setting 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

turn

We also hope to be able to turn left and right. Create a name called moveAngle new properties, which indicate the current moving value or rotation angle. In newPos() method based on moveAngle Attribute calculation angle:

Example

Please 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

Kuwa kama ko kawo kaki

Kuwa kama ko kawo kaki kuma saukiwar zuwa baya ko baya, baya ko baya a kai kai daga tsohon yanki zuwa kwanan yanki, kuma yana iya kai kai daga wani gaba zuwa wani gaba, kuma yana iya mayar da kai kai daga yamma zuwa kudu. Kuma a kai kai daga wani gaba zuwa wani gaba, yana iya mayar da kai kai daga yamma zuwa kudu.

Example

Try it yourself

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