# Calculating orientation in 3D

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

## Recommended Posts

Hi, I am trying to model a gun which will orient itself to a flying object automatically. I have managed to get the amount of rotation around the Z axis. But I am unable to get the orientation around the X axis. This is the code I have so far :
float angleX, angleZ;

vector3 dirVector = v2 - v1;

vector3 projTarget = dirVector;

// project this onto the XZ plane
projTarget.y = 0;
projTarget.normalize();
angleZ = AngleBetweenVectors(projTarget, v2);

// build new forward and right vector
vector3 up(0, 1, 0);
vector3 right = -CrossProduct(projTarget, up);
up = CrossProduct(dirVector, right);
vector3 forward = CrossProduct(projTarget, right);

// project the enemy vector onto YZ plane
projTarget = v2;
projTarget.x = 0;
projTarget.normalize();
angleX = AngleBetweenVectors(forward, projTarget);

//angleZ = AngleBetweenVectors(projTarget);

float dotProduct = DotProduct(v1, v2);

if(v2.x > 0)
{
angleZ = 90 - angleZ;
}
else
{
angleZ = angleZ - 90;
}

if(v2.z < 0)
{
angleX = 90 - angleZ;
}
else
{
angleX = angleZ - 90;
}

Quaternion q;


I am not sure if I am calculating the forward vector correctly.

##### Share on other sites
I'm not too sure how your code works but I would use a UVN rotation matrix to orient your gun towards the target. So you basically calc the 'lookat' or N vector (v2-v1), normalise it, then find the right (U) and up (V) vectors as you already do in the code. Then build the UVN matrix:

Ux Vx Nx 0
Uy Vy Ny 0
Ux Vz Nz 0
0 0 0 1

and mult all the gun's vert's with it.

Hope that helps.

• 18
• 29
• 11
• 21
• 16