I feel like this should be Unity 101, but I am completely stuck.
I have a gameobject that I want to rotate -90 degrees on the x axis if I click the left arrow, 90 degrees on the x axis if I click the right arrow, 90 degrees on the z axis if I click the up arrow and -90 degrees on the z axis if I click the down arrow. The object should take 1 second to do the rotation. To clarify a little further, from the perspective of a static camera, the object should appear to rotate in the same direction each time a given button is clicked.
When my object starts at an initial 0 rotation I can easily code this to work. However, once the object is at 90 degrees on the x axis, the object appears to rotate on the y axis instead of the z axis if I click up or down. I also notice this even in the unity editor if I manually slide the rotation values.
Any insight into how I can make the object always rotate in my desired location in world space regardless of the objects current rotation? I clearly don’t have a full grasp of Quaternions and rotations.
Here’s a quick script thanks to chatGPT that demonstrates what I’m talking about.
using System.Collections;
using UnityEngine;
public class CubeController : MonoBehaviour
{
public float rotationTime = 1f;
public KeyCode leftKey = KeyCode.LeftArrow;
public KeyCode rightKey = KeyCode.RightArrow;
public KeyCode upKey = KeyCode.UpArrow;
public KeyCode downKey = KeyCode.DownArrow;
private bool isRotating = false;
void Update()
{
if (!isRotating && Input.GetKeyDown(leftKey))
{
StartCoroutine(RotateObjectLocalX(-90f));
}
else if (!isRotating && Input.GetKeyDown(rightKey))
{
StartCoroutine(RotateObjectLocalX(90f));
}
else if (!isRotating && Input.GetKeyDown(upKey))
{
StartCoroutine(RotateObjectLocalZ(90f));
}
else if (!isRotating && Input.GetKeyDown(downKey))
{
StartCoroutine(RotateObjectLocalZ(-90f));
}
}
IEnumerator RotateObjectLocalX(float angle)
{
isRotating = true;
Quaternion targetRotation = transform.localRotation * Quaternion.Euler(angle, 0, 0);
Quaternion initialRotation = transform.localRotation;
float elapsedTime = 0f;
while (elapsedTime < rotationTime)
{
transform.localRotation = Quaternion.Slerp(initialRotation, targetRotation, elapsedTime / rotationTime);
elapsedTime += Time.deltaTime;
yield return null;
}
isRotating = false;
}
IEnumerator RotateObjectLocalZ(float angle)
{
isRotating = true;
Quaternion targetRotation = transform.localRotation * Quaternion.Euler(0, 0, angle);
Quaternion initialRotation = transform.localRotation;
float elapsedTime = 0f;
while (elapsedTime < rotationTime)
{
transform.localRotation = Quaternion.Slerp(initialRotation, targetRotation, elapsedTime / rotationTime);
elapsedTime += Time.deltaTime;
yield return null;
}
isRotating = false;
}
}