Quaternion LookAt function

Started by
1 comment, last by reaperrar 11 years, 11 months ago
Trying to rotate my character to face a certain point with a quaternion though he jitters as if overshooting the required rotation and having to rotate backward and forth.

Here's my code:


//Get Direction to target
Vec3 oNewDirection = a_oTargetPosition - GetWorldTranslate();
oNewDirection.Normalize();

//Get axis perpendiculr to forward dir and target dir to rotate around
Vec3 oRotationAxis = m_oDirection_Forward.Cross(oNewDirection);

//Get angle
float fRotationAngle = acos(Clamp(m_oDirection_Forward.Dot(oNewDirection), -1.0f, 1.0f));

//Invert angle if neccessary
if (m_oDirection_Right.Dot(oNewDirection) < 0.0f)
{
fRotationAngle *= -1.0f;
}

//Create new quaternion to rotate this object
Quaternion oTempQ = Quaternion(fRotationAngle, oRotationAxis);

//Rotate this objects quaternion by the new quaternion to face target
m_oRotation = m_oRotation * oTempQ;

//Normalize
m_oRotation.Normalize();

//Set Rotation
SetRotate(m_oRotation);


Is my logic correct?
Advertisement
I don't think you have to invert the angle if it's larger than pi/2. Other than that, at first inspection I don't see anything wrong with your code.

Perhaps you can capture the numbers from a situation where the code seems to be misbehaving, and then debug your code with that input.
I think the lookat function isn't working,,

Example...
The original dot product between the forward and new direction will equal:
0.99895191
The dot product between the new forward (after rotation is applied) and new direction then equals:
0.99904567

So it rotate towards but doesn't end up snapping to the new direction, the dot product should equal 1 after...

EDIT: Solved, wasn't normalizing the rotation axis result of the cross product.

This topic is closed to new replies.

Advertisement