- Home /
how to calculate resultant direction vector from a given set of vectors?
Hi, I am making a 2d game in which a player has to save the a character (which is in the middle of screen) from several zombies coming towards the character. I have setted up a triggered collider around the character(the one , a player has to save). if the moving zombie triggers the collider then the zombie chases it. then the character should run in opposite direction from the zombie. if there are several zombies inside the collider then the character should run in the resultant direction (like shown in the image ) (E-> Enemy zombies, P-> character).
Answer by Habitablaba · Jun 30, 2016 at 07:00 PM
You should spend some time reading up on vector math. What you have is 2 input vectors, one coming from each enemy, and you want to combine them to find a new direction.
Check it out:
To get the vector from the enemy to the player, simply use subtraction.
var vector = player.transform.position - enemy.transform.position;
This vector is actually telling you two things; direction and magnitude (distance). In your case, it sounds like we don't actually care about distance, just direction. So normalize the vector, which gives us the direction and a magnitude of 1.
vector.Normalize();
Now we can add together all of the vectors we have, which will give a new vector for the player to move in. You'll want to normalize this one as well, I imagine.
You'll need to keep track of which enemies are in the trigger area, and calculate their to-player vectors accordingly. These will need to be saved to a class variable so you can iterate over them later.
Hope this helps!
@Habitablaba I am calculating this vector in OnTriggerStay2D() method so that as long as the enemy is inside the collider it will update the resultant vector each physics update. Will it update the resultant vector considering all the enemies inside the trigger collider. I have done that, but its seems that the character is not moving in the appropriate direction.