Search code examples
javascriptmathcanvas2d-games

Enemy sprite takes a strange path towards the player


I'm trying to make a sprite in my canvas game constantly move towards the player until it collides. The relevant function that does this is the update() function:

Enemy.prototype.update = function(playerX, playerY) {
    // Rotate the enemy to face the player
    this.rotation = Math.atan2(this.y - playerY, this.x - playerX) - 2.35;

    // Move in the direction we're facing
    this.x += Math.sin(this.rotation) * this.speed;
    this.y += Math.cos(this.rotation) * this.speed;
}

this.x, this.y, this.rotation and this.speed are the X position, Y position, rotation, and speed of the enemy, respectively.

It kind of works, however the enemy gets about 300 pixels away from the player and then starts to veer off to the left and move away from the player, at a 90 degree angel from the direction it came towards the player.

Since this is kind of hard to explain, I recorded a quick video to help show the problem: http://www.screenr.com/AGz7

The enemy is the orange sprite and the player is the white one.

What kind of problem is there with the calculations I'm doing to make the enemy move towards the player?


Solution

  • From writing angle/movement code before, these might be errors:

    Instead of this.rotation = Math.atan2(this.y - playerY, this.x - playerX) - 2.35;

    Does

    this.rotation = Math.atan2(playerY - this.y, playerX - this.x);

    Give you the right rotation?

    Reasoning: Don't use magic constants, try to figure out why your formula is wrong.

    Instead of

    this.x += Math.sin(this.rotation) * this.speed;
    this.y += Math.cos(this.rotation) * this.speed;
    

    Try

    this.x += Math.cos(this.rotation) * this.speed;
    this.y += Math.sin(this.rotation) * this.speed;
    

    Reasoning: If your angles are 0 = east based (and if you use math library functions they are by default), then for an angle 0 you want maximum horizontal movement and no vertical movement - cos(0) = 1 and sin(0) = 0.