javascriptcanvasgame-ai

Problems making enemy follow moving player


Okay, so I want to make a javascript/html canvas game where the player is being followed by some enemies, and after a little bit of 'research' her is the most important part of my Monster (enemy) class:

  this.UpdateAngle = function() {
    this.dx = this.x - player.x;
    this.dy = this.y - player.y;
    this.angle = Math.atan2(this.dy, this.dx) * 180 / Math.PI;
    if (this.angle < 0) {
      this.angle += 2 * Math.PI;
    }
  }
  this.UpdateSpeed = function() {
    this.speedX = this.speed * Math.cos(this.angle);
    this.speedY = this.speed * Math.sin(this.angle);
  }
  this.Move = function() {
    this.UpdateAngle();
    this.UpdateSpeed();
    this.x += this.speedX;
    this.y += this.speedY;
  }

So what I meant to do here, was to calculate the angle from the enemy to the player with atan2() and then calculate how much I should move in the x and y axis by using cos() and sin(), the speed and the angle I calculated, and then just moved the calculated pixels.

This all seems to work well, until I move the player, then the enemies start to move in weird directions. I have no idea whats wrong, it would be awesome if someone could learn me how this is meant to be done. :D

You can see it in action here. *I have updated the code with PremierBromanov's suggestion.


Solution

  • Ok, so it was actually Premier Bromanov who answered this, thanks, but I can't accept a comment, which it was, so I will just do this to make it more clear, if anyone should come by and want the answer too. The math i did was a bit wrong, and here is how my code ended up looking like:

    this.UpdateAngle = function() {
      this.dx = player.x - this.x;
      this.dy = player.y - this.y;
      this.distance = Math.sqrt((this.dx*this.dx) + (this.dy*this.dy));
      this.angle = Math.atan2(this.dy,this.dx) * 180 / Math.PI;
    }
      this.UpdateSpeed = function() {
      this.speedX = this.speed * (this.dx/this.distance);
      this.speedY = this.speed * (this.dy/this.distance);
    }
    this.Move = function() {
      this.UpdateAngle();
      this.UpdateSpeed();
      this.x += this.speedX;
      this.y += this.speedY;
    }
    

    Thanks again to Premier Bromanov, this is his answer, and also to everyone else, this was my first post and i am glad how fast i got a response! (I was the slowest one here) :D