Calculating orientation in 3D

Started by
0 comments, last by just_haps 19 years, 6 months ago
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;
q.SetRotateXYZ(DegToRad(angleX), 0, DegToRad (angleZ));

I am not sure if I am calculating the forward vector correctly.
The more applications I write, more I find out how less I know
Advertisement
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.

This topic is closed to new replies.

Advertisement