- Home /
Rotating an object to target on the Z axis
I'm building a 2d game with airplanes, using the 2d-toolkit. I'm trying make and AI plane which would follow the player by rotating and moving towards him (I want it to only rotate on the Z axis), I'm using:
var deltaRotation = target.position - transform.position;
var rotation = Quaternion.LookRotation(deltaRotation);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * 3);
to rotate the plane: and this, to move it:
var direction: Vector3 = Vector3(speed, 0.0, 0.0);
transform.Translate(direction);
but the plane only rotates around the player using the X and Y axis, if the player move down/up it doesn't rotate on the Z axis.
And if I try to restrict the rotation to the Z axis by:
deltaRotation.y = 0;
deltaRotation.x = 0;
it doesn't rotate at all.
Answer by whydoidoit · Aug 20, 2012 at 04:17 PM
To start with you shouldn't go messing with the .x .y .z and .w properties of a Quaternion - they don't mean what you think they do and are a representation of the rotation in 4d space.
You could try getting the eulerAngles from the Quaternion.LookRotation and zero out the .x and .y in that before converting it back into a Quaternion.
var rotation = Quaternion.LookRotation(deltaRotation).eulerAngles;
rotation.x = rotation.y = 0;
var rotatingQuaternion = Quaternion.Euler(rotation);
Thanks, but it still doesn't rotate towards it's target on the Z axis, when I output rotation.z to the screen using the GUI it stays 0 all the time no matter where I move the target. If I remove rotation.x = rotation.y = 0; it rotates on the other axis, though.