0
\$\begingroup\$

I have a game object in my scene, and I want to know how can I calculate whether this game object rotating to the right or to the left.

For example :

if(check whether the transform rotated to the right)
{
    print("rotate to right");
}
else if(check whether the transform rotated to the left)
{
    print("rotate to left");
}
else
{
    print("no rotation");
}
\$\endgroup\$
2
\$\begingroup\$

I'd recommend using the properties of the cross product to check this, rather than relying on Euler angles.

Given a vector a & b, the cross product will point along the rotation axis that swings a toward b. Since Unity uses left-handed coordinates, you can take your left hand in a "thumbs-up" gesture and turn it so you fingers curl in the direction of rotation. Your thumb points along the direction of the cross product.

For example, here's how we'd detect rightward (positive) and leftward (negative) "yaw" rotation about the world's Y+ axis:

public enum RotationDirection {
    NoRotation,
    Leftward,
    Rightward
}

Vector3 oldForward
RotationDirection rotationDirection;

void Start() {
    oldForward = transform.forward;
}

void Update() {
    Vector3 cross = Vector3.Cross(oldForward, forward);

    if (cross.y > 0f) }
        rotationDirection = RotationDirection.Rightward;
    } else if (cross.y < 0f) {
        rotationDirection = RotationDirection.Leftward;
    } else {
        rotationDirection = RotationDirection.NoRotation;
    }    

    oldForward = transform.forward;
}
\$\endgroup\$
  • \$\begingroup\$ yes it is better way , thankyou very much for your help. @DMGregory \$\endgroup\$ – iman_sh Apr 23 '19 at 20:22
1
\$\begingroup\$

Do you have a rigidbody on it? Then you can check the angularVelocity field. If not, the best you can do is cache the previous orientation, then compare it to the current one. First let's define "right" and "left". To me, that means "clockwise about the z axis" and "counter clockwise about the z axis". What we want then is to do is this:

Quaternion oldRotation;
Quaternion currentRotation;
float zRotation = (Quaternion.Inverse(oldRotation) * currentRotation).eulerAngles.z;
if (z > 0) // we turned right
if (z < 0) // we turned left
if (z == 0) // we did not turn

Something like that should work. But if you have a rigidbody, do just use that.

\$\endgroup\$
  • \$\begingroup\$ It helps me but with some edits , Thanx \$\endgroup\$ – iman_sh Apr 23 '19 at 20:14
  • \$\begingroup\$ Great! Feel free to tell me the edits, then I can fix the answer for anyone looking in the future \$\endgroup\$ – gjh33 Apr 24 '19 at 13:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.