# Calculating angle between Z-Axis and target vector

## Recommended Posts

DOrmisher    100
I'm trying to calculate the angle between the Z-Axis of a turret on a tank, and the a vector from the tanks position and the targets position, so I can have the turret gradually rotate on it's local Y, and calculate the angle every frame, then when the angle is within 20 degrees either side, the tank entity goes into a different state. However, below you can see how I am doing it, but I seem to be getting some strange results.
CVector3 Matrix(2).RotateLocalY( ToRadians(20.0f*updateTime) );

CVector3 normZ = Normalise( Matrix(2).ZAxis() );
CVector3 normTargVec = Normalise( CVector3( Matrix().Position(), m_Enemy->Matrix().Position() ) );
double a = ToDegrees( acos( Dot( normZ, normTargVec ) ) );

if( fabs(a) < 20 )
m_State = Aim;

The tank's state does change at the moment, just seems to be at random times.

##### Share on other sites
bluntman    255
Well I don't know what your Matrix(2) stuff is about, what library are you using? The method for calculating the angle looks correct though, assuming your maths library usage is correct. The ZAxis function for your matrix will (unless it is weird) return an already normalized vector (if your matrix is composed purely of translation and rotation, as it is in the code shown).