- Home /
Rotating cube steadily around world axis not working properly
Hey,
im kind of stuck in a project im working on. Goal is to rotate a cube by 90° over a set amount of time when a directional key is pressed. I want to rotate it around the world axis as my camera is always facing in the forward z direction, directly facing the cube.
Im using a Coroutine to smoothly turn the cube which is almost working as intended - initally turning works perfectly but as soon as i for example rotate the cube upwards the next rightwards rotation is around the local axis of the cube in question.
Struggling to figure out where the problem is as to me it seems like it should rotate around the world axis from the code in the script >.<
Code blocks in question are below, thanks in advance!
The place where the coroutines are called:
if(Input.GetButtonDown("Horizontal") && Input.GetAxisRaw("Horizontal") > 0)
{
if (rotationOnGoing == false)
{
// turn cube rightwards
StartCoroutine(RotateCube(objHit, -90, Vector3.up, cubeTurnTime));
}
}
else if(Input.GetButtonDown("Horizontal") && Input.GetAxisRaw("Horizontal") < 0)
{
if(rotationOnGoing == false)
{
// turn cube leftwards
StartCoroutine(RotateCube(objHit, 90, Vector3.up, cubeTurnTime));
}
}
else if (Input.GetButtonDown("Vertical") && Input.GetAxisRaw("Vertical") > 0)
{
if(rotationOnGoing == false)
{
// turn cube upwards
StartCoroutine(RotateCube(objHit, 90, Vector3.right, cubeTurnTime));
}
}
else if (Input.GetButtonDown("Vertical") && Input.GetAxisRaw("Vertical") < 0)
{
if (rotationOnGoing == false)
{
// turn cube downwards
StartCoroutine(RotateCube(objHit, -90, Vector3.right, cubeTurnTime));
}
}
The coroutine handling the cube rotation over time:
IEnumerator RotateCube(Transform objToRotate, float angle, Vector3 axis, float duration)
{
float rotationSpeed = angle / duration;
float deltaAngle = 0;
Quaternion startRotation = objToRotate.rotation;
Debug.LogWarning(objToRotate.rotation);
rotationOnGoing = true;
if (angle > 0)
{
while (deltaAngle < angle)
{
deltaAngle += rotationSpeed * Time.deltaTime;
deltaAngle = Mathf.Min(deltaAngle, angle);
objToRotate.rotation = startRotation * Quaternion.AngleAxis(deltaAngle, axis);
yield return null;
}
}
else if (angle < 0)
{
while (deltaAngle > angle)
{
deltaAngle += rotationSpeed * Time.deltaTime;
deltaAngle = Mathf.Max(deltaAngle, angle);
objToRotate.rotation = startRotation * Quaternion.AngleAxis(deltaAngle, axis);
yield return null;
}
}
Debug.Log("Coroutine finished.");
rotationOnGoing = false;
yield break;
}