How can I fix rotation of Z axis to 0?
Hello,
I am trying to right a bird controller.
In this script I am rotating object on Vector.up axis.
Also during elevation I rotate forward axis of object around transform.right axis to make birds head look towards upward or downward. (I limit that rotation with 45 degree)
In theory in shouldn't mess with Z axis (transform.right) of object. It should stay same. But after I run script for a little time, orientation of bird starts to breaking down.
Here is the script:
void Update () {
float hor = Input.GetAxis("Horizontal");
float ver = Input.GetAxis("Vertical");
float elev = Input.GetAxis("Elevation");
float xAngle = transform.rotation.eulerAngles.x;
bool eliminateHeight = false;
if ((xAngle > 0 && xAngle<180 && transform.position.y < minHeight) || (xAngle < 360 && xAngle > 180 && transform.position.y > maxHeight))
{
eliminateHeight = true;
}
float prevHeight = transform.position.y;
cc.Move( -transform.forward*ver*speed);
if (eliminateHeight)
{
transform.position =new Vector3(transform.position.x, prevHeight , transform.position.z);
}
transform.Rotate(Vector3.up*hor,Space.World);
if (elev == 0)
{
if (xAngle < 180f)
{
if (xAngle > 1f)
{
transform.rotation = Quaternion.Slerp(transform.rotation, transform.rotation * Quaternion.Euler(-1, 0, 0), Time.deltaTime * 40);
}
else if (xAngle > 0)
{
transform.rotation = transform.rotation * Quaternion.AngleAxis(-xAngle, transform.right);
}
}
else
{
if (xAngle < 359)
{
transform.rotation = Quaternion.Slerp(transform.rotation, transform.rotation * Quaternion.Euler(1, 0, 0), Time.deltaTime * 40);
}
else if (xAngle < 360)
{
transform.rotation = transform.rotation * Quaternion.AngleAxis((360 - xAngle), transform.right);
}
}
} else
{
if( ((xAngle>360-45||xAngle==0) || xAngle<45) || ((xAngle < 360 - 45 && xAngle>180 && elev < 0) || (xAngle > 45 && xAngle < 180 && elev > 0)))
transform.Rotate(-elev, 0, 0);
}
}
So I decided to write a if condition that checks z axis rotation and when z axis is not 0 it should set it to 0. But I couldn't manage to set only z axis to zero.
Here is the if condition
if (zAngle != 0)
{
print("fixing z");
if (zAngle > 180)
{
transform.rotation = Quaternion.AngleAxis(-(360 - zAngle), transform.forward);
}else
{
transform.rotation = Quaternion.AngleAxis(-zAngle, transform.forward);
}
}
How can i set z axis rotation to 0 without altering other axes.
Edit: I fount the reason of why z axis rotation is changes. It is due to obstacles that bird encounter during its flight.
Your answer
Follow this Question
Related Questions
Rotating an Object (To Face Another Object) Only on X and Y Axis 3 Answers
Quaternions rotation stuck 0 Answers
Assign an object rotation along a single axis from other object's rotation. 0 Answers
How to have objects rotate around a given point that are scripted to face the player 1 Answer
Rotate a GameObject a fixed amount on key press struggles. Stops at 180. 1 Answer