Finding Vectors with 2 points

Serial picture Serial · Jun 27, 2013 · Viewed 13k times · Source

Im helping my friend out with a pygame but we are stuck

so were are trying to get the direction of a projectile but we cant find out how

for example:

[1,1] will go SE

[1,-1] will go NE

[-1,-1] will go NW

and [-1,1] will go SW

we need an equation of some sort that will take the player pos and the mouse pos and find which direction the projectile needs to go

here is where we are plugging in the vectors:

def update(self):

    self.rect.x += self.vector[0]
    self.rect.y += self.vector[1]

then we are blitting the projectile at the rects coords

Answer

abarnert picture abarnert · Jun 27, 2013

So, first you want to get the vector distance from the player to the cursor. Subtracting two points gives you the vector between them:

distance = [mouse.x - player.x, mouse.y - player.y]

Now, you want to normalize that to a unit vector. To do that, you just get the norm (by the Pythagorean theorem), and divide the vector by the norm:

norm = math.sqrt(distance[0] ** 2 + distance[1] ** 2)
direction = [distance[0] / norm, distance[1] / norm]

Finally, you want the velocity vector. You get that by multiplying the direction (the unit vector) by the speed.

Since you want a bullet fired to the SE to have vector [1, 1], you (presumably) want all bullets to move at the speed of that velocity vector, which is sqrt(2) (by the Pythagorean theorem again). So:

bullet_vector = [direction[0] * math.sqrt(2), direction[1] * math.sqrt(2)]

And that's it.


Here you can see this code working. (That's an interactive visualizer, so you can step through it piece by piece if there's any part you don't understand.)

I create a player at [10.0, 25.0], and a mouse pointer off a generally (but not exactly) south-easterly direction at [30.0, 70.0], and bullet_vector ends up as [0.5743665268941905, 1.2923246855119288], a vector pointing in that same general south-easterly direction with speed sqrt(2).

This shows that it can go southeast (if you want to go exactly southeast, change line 8 to mouse = Point(30.0, 45.0)), it can go in directions other than the 8 compass points, and it always goes at the same speed.