I know there is a way to check the position of an object along x, y and z, but is it possible to check an objects rotation along x, y and z also? My intention for this is to rotate a cube by 90 degrees along the y axis and to check its rotation using an if statement to trigger an event. I have placed an example of what I would like to do below.
if(target is rotated at 90 along y-axis)
An object can be rotated “around” various axis but isn’t rotated “along” an axis (just a small nit). Given an object, you can access its Transform properties. One of the transform properties is a property called “rotation” which is the object’s rotation defined as a “quaternion”. A quaternion object has a property called “eulerAngles” which is a Vector3 representing the objects rotation around the x, y and z axis.
So … given an object called MyObject … the following can be used:
if (myObject.transform.rotation.eulerAngles.y == 90)
// Do something
While angle decreasing
Mathf.DeltaAngle() tells you the angular distance between two Euler axis. Saving the deltaAngle from the last frame enables checking if the delta is decreasing. This works great if something is continually rotating along a single axis at fast speeds (less than 180 degrees a frame).
public IEnumerator RotateTo90()
float deltaAngle = 360;
float lastDeltaAngle = deltaAngle;
var amountToRotate = angularSpeed * Time.deltaTime;
deltaAngle = Mathf.Abs(Mathf.DeltaAngle(this.rotation.eulerAngles.y, 90));
isAngleDecreasing = deltaAngle < lastDeltaAngle;
yield return null;
} while (isAngleDecreasing);
Alternate Quaternion.Dot method
I couldn’t get this method to work well. It is likely more performant. It may work for your scenario. Quaternion.Dot can be used to see how close two rotations are to one another. It returns 1 or -1 when the rotations coincide and 0 when they’re opposite directions.
Quaternion targetAngle = Quaternion.Euler(0, 90, 0);
float precision = 0.9999f;
if (Mathf.Abs(Quaternion.Dot(this.transform.rotation, targetAngle)) > precision)
// do something