


This is all fine and good, but the square root function and the two divisions can slow things down if you're using it a lot every frame (and the trigonometry version is slower yet). The above will give you a vector from player to enemy that will travel 12 per iteration, regardless of the angle of the vector or how far away enemy was from player. Divide by magnitude and multiply by desired speed The speed you want the projectile to travel In 2D gaming, you often use unit vectors along with multipliers to calculate a projectile's vector based on the speed you want it to travel at.
DIRECTION OF VECTOR 2D CODE
You can also use trigonometry to calculate it, but it is slower:īoth code blocks above will give you the same unit vector. To get a unit vector, the easiest and most accurate way is to divide each part of the vector by the vector's magnitude (length). Think about the actual length of the line (it's magnitude) and you'll understand why (1,1) is not a unit vector. Notice that while (1,0) is a unit vector, (1,1) is not. Unit vector and normalized vector are often used interchangeably. To get a unit vector from any old vector, you "normalize" that vector, which gives you a new vector with the same direction but a magnitude of 1. The vector can be pointing in any direction, but the magnitude will always be 1. A unit vector is a vector with a magnitude (distance) of 1. Here's a quick description of a unit vector for those that don't know.
