- Home /
Rotate cube non-relative to current rotation.
Hey People,
so basically i want to rotate my cube by lets say 90 degrees to the left. Thats working.
Now if i rotated it up twice, which results in the cube standing on its "head", pressing the left arrow will make it rotate to its right.
How do i perform these rotations non-relative to whats already been there?
void Update()
{
if (Input.GetKeyDown(KeyCode.DownArrow)&& !isRotating)
{
StartCoroutine(Rotate(Vector3.down, 90, 0.8f));
}
if (Input.GetKeyDown(KeyCode.UpArrow)&& !isRotating)
{
StartCoroutine(Rotate(Vector3.up, 90, 0.8f));
}
if (Input.GetKeyDown(KeyCode.LeftArrow) && !isRotating)
{
StartCoroutine(Rotate(Vector3.left, 90, 0.8f));
}
if (Input.GetKeyDown(KeyCode.RightArrow) && !isRotating)
{
StartCoroutine(Rotate(Vector3.right, 90, 0.8f));
}
}
IEnumerator Rotate(Vector3 axis, float angle, float duration = 1.0f)
{
isRotating = true;
Quaternion from = transform.rotation;
Quaternion to = transform.rotation;
to = Quaternion.Euler(axis angle);
float elapsed = 0.0f;
while (elapsed < duration)
{
transform.rotation = Quaternion.Slerp(from, to, elapsed / duration);
elapsed += Time.deltaTime;
yield return null;
}
transform.rotation = to;
isRotating = false;
Debug.Log("Fin");
}
}
Answer by knobblez · Dec 01, 2018 at 09:31 PM
Is the controller and the cube on the same gameObject? If you sit on a flying drone, then fly upside-down, down would become up and vice versa.
Also check out rigidbodies and AddForce.
https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html