Clamping rotation of a game object on the x axis
I am trying to limit the rotation of an object which rotate on the x axis, I would like the object stop is rotation before the top and bottom. I have looked everywhere and read and try a lot of things but I cannot figure it out. here is my script for the mouse, I am doing it for a touch pad too but that is not my problem. The clamping doesn't work, it clamp one way and then I cannot move my mouse up. it stays near the max clamping value. I cannot figure out why. I have tried everything.
void FixedUpdate() { #if UNITY_EDITOR || UNITY_STANDALONE_OSX || UNITY_STANDALONE_WIN || UNITY_WEBPLAYER || UNITY_WEBGL if (Input.GetMouseButton(0) || Input.GetMouseButtonDown(0) || Input.GetMouseButtonUp(0)) { ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit, touchInputMask)) {
GameObject recipient = hit.transform.gameObject;
if (Input.GetMouseButtonDown(0))
{
isRotating = false;
}
if (Input.GetMouseButton(0))
{
rotationX = Input.GetAxis("Mouse X") * rotationRate;
rotationY = Input.GetAxis("Mouse Y") * rotationRate;
//left and right
//up and down
if (Mathf.Abs(rotationX) < Mathf.Abs(rotationY))
{
if (rotationY < 0)
{
targetItem.transform.Rotate(Vector3.right, -rotationRate * Time.deltaTime);
}
else
{
targetItem.transform.Rotate(Vector3.right, rotationRate * Time.deltaTime);
}
}
float minRotation = -45;
float maxRotation = 45;
Vector3 currentRotation = targetItem.transform.localRotation.eulerAngles;
currentRotation.x = Mathf.Clamp(currentRotation.x, minRotation, maxRotation);
targetItem.transform.localRotation = Quaternion.Euler(currentRotation);
Debug.Log(currentRotation);
}
}
}
endif
I think ins$$anonymous$$d of
targetItem.transform.localRotation = Quaternion.Euler(currentRotation);
you can assign the value like
targetItem.transform.localRotation = new vector3(currentRotation.x ,targetItem..transform.localRotation .y,targetItem..transform.localRotation .z)