I have a player and an enemy, both have x and y values, and I want to move the enemy to the player and have them 'touch' over time in a speed that I can determine, I tried calculating the angle between the enemy, the player, and the 0, 0 point on the canvas using trigonometry but it just doesn't work right, most the times the angle is Not A Number(NaN) or goes in a direction different that the player. *The code is not in the same file, I copy pasted the relevant parts of the code and pasted them together. Here is my code, any help would be greatly appreciated:

// Creating a visual triangle and storing the length of it's vertices distance(size)
    line(enemy.x, enemy.y, 0, 0);
    lineOne = dist(enemy.x, enemy.y, 0, 0);
    line(player.x, player.y, 0, 0);
    lineTwo = dist(player.x, player.y, 0, 0);
    line(player.x, player.y, enemy.x, enemy.y);
    lineThree = dist(player.x, player.y, enemy.x, enemy.y);
// Calculating the angle itself using the cosine rule
angle = acos((lineThree * lineThree + lineOne * lineOne - lineTwo * lineTwo) / (2 * lineThree * lineTwo));

//Function to move  the enemy(based on a suggestion made in this website)
this.move = function()
        if(angle != NaN && angle >= 0)
            this.x -= 2 * cos(angle) + sin(angle) * 2;
            this.y += 2 * sin(angle) + cos(angle) * 2;

The if statement that checks if the angle is not a NaN value is required because it happens a lot for some reason, it also checks if it is bigger or equal to zero, because if it isn't the enemy just doesn't show at all.

Thank you for your time!


1 Answer 1


You're overcomplicating it. Let's say the object you want to move is at (x1; y1) and the player is at (x2; y2)

The vector pointing from the object to the player is d = (x2 - x1; y2 - y1) you can normalize this by dividing by it's own length: normalized = d / |d|. And then just multiply it with a speed value and add it to the object's position.

Even if you wanted to calcilate the angle (which you don't need in this case) you could just get the distances of the player and the object on the x and y axis and use atan2 to find the angle: angle = atan2(y2 - y1, x2 - x1)

Also, converting an angle to a vector is a lot easier too, the vector pointing in that direction would simply be (cos(angle); sin(angle))


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .