- Home /
Mathf.Clamp acts strange when going below 0
So, I'm having this problem where my mathf.clamp works for the min value, but not on the max. To be more specific, everytime I rotate my object (bound to mouse input) below 0, it teleports back to the min value set for the clamp. I wish I could show you in a video. I am trying to move a characters arm (with gun) up and down on the x axis. I've been looking all over the web, but can't find what I did wrong. Thx in advance!
Code:
using UnityEngine;
using System.Collections;
public class Right_Arm_Rotator : MonoBehaviour {
private float rotateSensitivity = 2f;
private float mouseInputNumber;
private Vector3 eulerAnglesStored;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
mouseInputNumber = -Input.GetAxis("Mouse Y") * rotateSensitivity;
transform.Rotate(mouseInputNumber, 0, 0);
eulerAnglesStored = transform.eulerAngles;
eulerAnglesStored.x = Mathf.Clamp(eulerAnglesStored.x, -100, 30);
transform.eulerAngles = eulerAnglesStored;
}
}
Answer by mikelortega · May 30, 2016 at 11:55 AM
Unity and other engines represent rotations using quaternions. Euler angles are just a representation of the quaternion to make it understandable.
Every time you assign Euler angles Unity converts them to a quaternion. When you ask Unity for Euler angles it converts the quaternion but it can be completely different from the original angles you set up.
You should work with your eulerAnglesStored but I think the problem is in line 21, there you are transforming the quaternion to Euler and you might be getting angles you don't expect.
HI $$anonymous$$ikelo, thanks for awnsering :)
I'm honestly a bit lost now. I get what you're saying, but I don't think I have enough understanding of quaternions to come up with an alternative way of doing this. What would you suggest me writing ins$$anonymous$$d of what I did?
Use your eulerAnglesStored to do your rotation, but do not overwrite it in line 21 with eulerAnglesStored = transform.eulerAngles;