2D normalized vector question

Started by
0 comments, last by h4tt3n 14 years, 10 months ago
Ok this is more of a seeing if I am thinking about this right question. Currently I am porting the XNA2D tutorial from the creators club to python and pyglet. While I am doing so I am trying to refresh my brain on some math concepts. Basically I am firing a cannon ball from a cannon rotated at a certain angle. This is the code to calculate the velocity. This is close to exactly what the XNA tutorial uses but I had to do some research to find out what exactly the trig trick is that they used.

ball.velocity = ([8.0*i for i in (
                                math.cos(self.cannon.rotation*(math.pi/180)),
                                math.sin(self.cannon.rotation*(math.pi/180)))])




they stated in the tutorial that it is a trig trick to get a unit vector. basically my assumption would be that the way the velocity works is by giving the slope of the vector based off the angle. and then adding the velocity to the position of the ball moves the ball along the slope of the hypotenuse. now the part I can't figure out is how it gives a unit vector. EDIT: been racking my brain with pen and paper and I think I got it. hopefully you guys can reassure me on my math. The length of a 2d vector we will call v is ||v|| = sqrt(vx^2 + vy^2) a normalized 2d vector has the length of 1 Under the assumption that you can break any triangle into a perfect 45, 45, 90 where T = theta we get the SinT = 1/sqrt(2) and CosT = 1/sqrt(2) So creating a vector defined as (CosT, SinT) we get ||v|| = sqrt(CosT + SinT) = sqrt(1/sqrt(2) + 1/sqrt(2)) which means ||v|| = (sqrt(1)/2 + sqrt(1)/2) = (1/2 + 1/2) = 1 so ||v|| = 1 and is there for a normalized vector. [Edited by - blewisjr on June 27, 2009 10:09:02 PM]
Advertisement
Hi there,

Basically, to get a unit vector or normalised vector, all you need to do is divide each vector component with the magnitude of the vector:

N = V/r

where N is the normalised vector, V is the vector, and r is the vector magnitude.

The x component, Nx = Vx/r, is the same as cosine to the angle of the vector. Similarly, the y component is sine to the angle. You can then get the actual angle with Atan2(Ny, Nx)

It seems like you want to do the reverse, you got the angle and want the unit vector. In this case

Nx = cos(angle)
Ny = sin(angle)

From your source it appears that the angle probably is in radians, not degrees. To convert from degs to rads just multiply the angle with 2*pi / 360 (or pi / 180).

This unit vector tells you the angle to shoot the ball. To change the firing velocity, multiply the unit vector with a scalar number, a "firing strength coefficient", or whatever you want to call it.

BallVel.x = N.x * Strength
BallVel.y = N.y * Strength

That should do it. Have fun.

Cheers,
Mike



This topic is closed to new replies.

Advertisement