I'm new with Unity development and I'm having some issues rotating GameObjects.
I want to make and object rotate -90 degrees each time you call a function. At this moment I can make it rotate around its Y and Z axis and there's no trouble, however, if i change the parameters so it rotates around X it gets stuck after rotating from -90º (270º actually) to 180º.
Here's the code I'm using for testing:
public class RotateCube : MonoBehaviour
{
GameObject cube;
bool rotating;
private void Start()
{
cube = GameObject.Find("Cube");
rotating = false;
}
private void Update()
{
if (!rotating)
{
StartCoroutine(Rotate());
}
}
private IEnumerator Rotate()
{
rotating = true;
float finalAngle = SubstractNinety(cube.transform.eulerAngles.x);
while (cube.transform.rotation.eulerAngles.x != finalAngle)
{
cube.transform.rotation = Quaternion.RotateTowards(cube.transform.rotation, Quaternion.Euler(finalAngle, cube.transform.rotation.eulerAngles.y, cube.transform.rotation.eulerAngles.z), 100f * Time.deltaTime);
yield return null;
}
cube.transform.rotation = Quaternion.Euler(finalAngle, cube.transform.rotation.eulerAngles.y, cube.transform.rotation.eulerAngles.z);
yield return null;
rotating = false;
}
private float SubstractNinety(float angle)
{
if (angle < 90)
{
return 270f;
}
return angle - 90;
}
}
I'm updating all the coordinates in Quaternion.Euler in each iteration because I want the user to be able drag the object while it's rotating, but I wouldn't mind if the solution requires to define the Quaternion before the loop.
Why do you bother going through the eulerAngles ?
When using the
.eulerAnglesproperty to set a rotation, it's important to understand that although you provide X, Y, and Z rotation values to describe your rotation, those values are not stored in the rotation. Instead, the X, Y, and Z values are converted to the internalQuaternionformat.When reading the
.eulerAnglesproperty, Unity converts the internalQuaternionrepresentation of the rotation to Euler angles. Because there is more than one way to represent any given rotation using Euler angles, the values you read back may be quite different from the values you assigned. This can cause confusion if you try to incrementally increase values to produce animation .To avoid these kinds of problems, the recommended way to work with rotations is to avoid relying on consistent results when reading
.eulerAngles, particularly when trying to incrementally increment a rotation to produce animation. For better ways to accomplish this, see the Quaternion * operator .
Rather use Quaternion directly! Simply add the desired rotation to the existing one using the * operator
using UnityEngine; using System.Collections; public class Rotate : MonoBehaviour { public Space m_RotateSpace; public float m_RotateSpeed = 20f; // Update is called once per frame void Update() { transform.Rotate(Vector3.up * m_RotateSpeed * Time.deltaTime, m_RotateSpace); } }