1
\$\begingroup\$

i want to apologize if this seems so basic, but I'm having trouble having an Enemy move in my Player's Direction in a 2D Top-Down game.

I already saw a lot of other answers but they all use the .LookAt() and .Forward but i'm not using rotations so i cannot just move them in the direction they are looking at, i just need to move them along X and Y, and i managed to do a pretty horrible workaround :

//I tried getting the difference between player and enemy positions, but this is relative, and slows down the closer it gets to the player.

Vector2 distance = new Vector2(player.position.x - enemy.position.x, player.position.y - enemy.position.y);

enemy.AddForce(distance * walkspeed);

So, how could i make the Enemy move in the direction the Player is, but with a constant speed?

\$\endgroup\$
  • 1
    \$\begingroup\$ distance.Normalize() \$\endgroup\$ – DMGregory Nov 28 '15 at 20:46
  • \$\begingroup\$ Any example of how to implement it? \$\endgroup\$ – DS94 Nov 28 '15 at 20:50
6
\$\begingroup\$

To get a constant rate of movement for your walkspeed, you can normalize your distance between the player and the enemy.
A normalized vector still points to its original direction, however it has a length of 1, thus, getting you constant results when multiplying with your walkspeed.

The math behind it, for a vector v to its normalized version vn:

vn = normalize(v)
<=> v / length(v)
<=> v / sqrt(v.x * v.x + v.y * v.y)

In Unity, you can simply use the normalized property of a Vector. In your case, this would be:

Vector2 distance = new Vector2(player.position.x - enemy.position.x, player.position.y - enemy.position.y);
distance = distance.normalized;

If you multiply this vector with your walkspeed variable, it will always have a length of walkspeed, provided, that the initial distance is greater than 0.

\$\endgroup\$
1
\$\begingroup\$

Im really surprised nobody mentionned Vector2.MoveTowards().

Here's the method definition:

public static Vector2 MoveTowards(Vector2 current, Vector2 target, float maxDistanceDelta);

you would use it as such:

Vector2.MoveTowards(player.position, enemy.position, someValueYouDetermine);

Moves a point current towards target.

This is essentially the same as Vector2.Lerp but instead the function will ensure that the speed never exceeds maxDistanceDelta. Negative values of maxDistanceDelta pushes the vector away from target.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.