# Best way to find yaw ,pitch form a vector?

This topic is 2919 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi
I'm working on an artillery simulation, my partner is writing the physics class and I'm writing the artillery part, the artillery should be tilted according to the terrain.
I'm supposed to provide my partner with the absolute pitch,yaw of the canon (relative to the world)
After googling I couldn't find a simple & reliable way to decompose a matrix/quaternion so here's what I came up with

I'm working on XNA so the code is c# + XNA classes but the algorithm should be clear...

For the pitch:

public static float AbsolutePitch(Vector3 forward){	Vector3 projected = forward;	projected.Y = 0;	float a, b, c;	a = forward.Length();	b = projected.Length();	c = forward.Y;	// sin(pitch) = c/a	// pitch=aSin(c/a);	float angle = (float)Math.Asin(c / a);	// The sign is embedded in the asin since c=forward.Y not |forward.Y|	return MathHelper.WrapAngle(-angle);}

For the yaw:

public static float AbsoluteYaw(Vector3 forward){	Vector3 projected = forward;	projected.Y = 0;	projected.Normalize();	//(0,0,-1), XNA uses a right-handed coordinate system	Vector3 worldBackward= Vector3.Backward; 	// Used dot product to get the angle	float angle = (float)Math.Acos(Vector3.Dot(worldBackward, projected));	// Used cross product to get the sign of the angle	float sign = Math.Sign(Vector3.Cross(worldBackward, projected).Y);	angle *= sign;            	return MathHelper.WrapAngle(angle);}

I don't think the pitch function will cause me trouble, it should be fast enough, but the yaw function isn't perfect, it requires calculating dot & cross products...besides, the function wont work when forward is equal to (0,1,0)

Any suggested improvements? [looksaround] cuz performance really counts in the simulation...

##### Share on other sites
Are your world basis vectors arbitrary vectors? If not, and you are using (1,0,0), (0,1,0), (0,0,1), you can use the fact that they have two zeros and a one. This simplifies the vector products.

I have not tested it, but something like the following should work.
double pitch = Math.Acos(v.Y);double yaw = Math.Atan2(v.X, -v.Z);yaw = yaw < 0 ? 2 * Math.PI + yaw : yaw;  // if you want [0,2pi] instead of [-pi,pi]

EDIT: Oops, I think the arguments to atan2 were wrong.

##### Share on other sites
Thanks for you're help!
Since English isn't my main language, I had problems finding out what words I should look for :)

1. 1
Rutin
33
2. 2
3. 3
4. 4
5. 5

• 9
• 13
• 85
• 11
• 10
• ### Forum Statistics

• Total Topics
632969
• Total Posts
3009599
• ### Who's Online (See full list)

There are no registered users currently online

×