- Home /
Clamping rotation doesn't work when local axis is different from global
Hey guys, I've really been stuck on this for a while.
I've created a simple scene in Unity whereI can control a cubes rotation on the x and z axis through keyboard input. I don't want the cube to be able to rotate all the way around, so I have added an if statement to clamp the rotation:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeRotate : MonoBehaviour
{
void Update()
{
float zAxis = -Input.GetAxis("Horizontal");
float xAxis = Input.GetAxis("Vertical");
if ((gameObject.transform.rotation.z < 0.25f && zAxis > 0f) ||
(gameObject.transform.rotation.z > -0.25f && zAxis < 0f))
{
gameObject.transform.Rotate(new Vector3(0, 0, 1), zAxis);
}
if ((gameObject.transform.rotation.x < 0.25f && xAxis > 0f) ||
(gameObject.transform.rotation.x > -0.25f && xAxis < 0f))
{
gameObject.transform.Rotate(new Vector3(1, 0, 0), xAxis);
}
}
}
It works fine when the local axis is the same as the global axis, but when I rotate the cube 180 degrees it keeps spinning. I have tried only rotating the cube 90 degrees on the y-axis and it seems that the cube can rotate more and more the further away from 0 (on the y axis) it gets.
Why aren't the if statement "clamps" working when the cube is rotated on the y-axis and how can I combat this?
I have attached a short video example, for better understanding :)
I hope you guys can help me out!! And be safe out there