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!