Reputation: 138
I am trying to have some enemies run away from my player. I found code to move toward the play and made it the opposite. The problem is they speed up really fast when running away. If i make the code back to running towards the character they move at a normal pace. Why is this?
Running away
Vector2 velocity = new Vector2((transform.position.x - player.position.x) * speed, (transform.position.y - player.position.y) * speed);
rigidbody2D.velocity = velocity;
running towards
Vector2 velocity = new Vector2((transform.position.x - player.position.x) * speed, (transform.position.y - player.position.y) * speed);
rigidbody2D.velocity = -velocity;
Upvotes: 0
Views: 1020
Reputation: 1377
I imagine the characters would actually slow down as they approach you... that's what the code you wrote would do.
Basically, you have (End - Start) * Speed
... which means that the length of End - Start
is multiplied by speed. So if the character is 5m away, velocity = 5m * speed, etc.
What you need is ((End - Start) / (End - Start).Length()) * Speed
.
By dividing by the length of End - Start
, you remove the distance from the equation, and get purely a direction multiplied by the wanted speed.
Upvotes: 1