I would like to limit my cameras rotation on the x axis. I attempted to employ
Mathf.Clamp(yRotation, -45, 45) but this only limits the maximum value of the float.
The camera will then be able to rotate 360 degrees but only 45 at a time.
How do I limit the transform.rotation.x between 45 degrees and -45 degrees?
I do know this is asked allot but I haven’t been able to put others examples to work for me.
My Code:
public class RotateView : MonoBehaviour {
//Rotation Sensitivity
public float RotationSensitivity = 35.0f;
//Rotation Value
float yRotate = 0.0f;
// Update is called once per frame
void Update () {
//Rotate Y view
yRotate = Input.GetAxis ("Mouse Y") * RotationSensitivity;
transform.Rotate (new Vector3 (-yRotate, 0.0f, 0.0f) * Time.deltaTime);
}
}
Limiting rotation is one of the uglier questions on Unity Answers. Lots of questions go unanswered, many answeres are flawed, and right answers are often specific to the situation and cannot be generalized. Here is one solution that works well as long as you don’t have to deal with gimble lock (which you will not have to do based on the code I see). Note this code never reads from eulerAngles. It only sets it. This is a safe way to approach manipulating eulerAngles:
using UnityEngine;
using System.Collections;
public class bug1 : MonoBehaviour {
//Rotation Sensitivity
public float RotationSensitivity = 35.0f;
public float minAngle = -45.0f;
public float maxAngle = 45.0f;
//Rotation Value
float yRotate = 0.0f;
// Update is called once per frame
void Update () {
//Rotate Y view
yRotate += Input.GetAxis ("Mouse Y") * RotationSensitivity * Time.deltaTime;
yRotate = Mathf.Clamp (yRotate, minAngle, maxAngle);
transform.eulerAngles = new Vector3 (yRotate, 0.0f, 0.0f);
}
}
Solved this worked fine for me.