- Home /
clamp rotation the other way?
what if you wanted to clamp a rotation to be between 90 and 270, so that you could look up and down, but it flips the other way! this would happen when the quaternion value "0" is between the min clamp and max clamp. in this case, what would you do?
more specifically, i have this:
using UnityEngine;
using System.Collections;
public class CameraController : $$anonymous$$onoBehaviour {
public int Sensitivity;
private float $$anonymous$$ouseY;
private float $$anonymous$$ouseYSet;
private float CameraAngle;
public GameObject CameraTarget;
void Start () {
}
void Update () {
// Rotation controls
$$anonymous$$ouseY += Input.GetAxisRaw ("$$anonymous$$ouse Y");
transform.localRotation = Quaternion.Euler ($$anonymous$$athf.Clamp (transform.localRotation.x, 90, -90), transform.localRotation.y, transform.localRotation.z);
transform.localPosition = new Vector3 (transform.localPosition.x, $$anonymous$$athf.Clamp (transform.localPosition.y, CameraTarget.transform.localPosition.y, CameraTarget.transform.localPosition.y + 50), $$anonymous$$athf.Clamp (transform.localPosition.z, CameraTarget.transform.localPosition.z + 25, CameraTarget.transform.localPosition.z + 50));
if ($$anonymous$$ouseYSet != $$anonymous$$ouseY)
{
transform.localRotation = Quaternion.Euler (transform.localRotation.x - ($$anonymous$$ouseY - $$anonymous$$ouseYSet) * Sensitivity * 10, transform.localRotation.y, transform.localRotation.z);
transform.localPosition = new Vector3 (transform.localPosition.x, transform.localPosition.y - ($$anonymous$$ouseY - $$anonymous$$ouseYSet) * Sensitivity * 10, transform.localPosition.z + ($$anonymous$$ouseY - $$anonymous$$ouseYSet) * Sensitivity * 10);
$$anonymous$$ouseYSet = $$anonymous$$ouseY;
}
}
}
also the color of the scene background flashes sometimes when rotating up and down
Answer by aldonaletto · Dec 25, 2014 at 10:19 PM
This is a recurrent error: localPosition is a Quaternion, a weird creature, and not those nice angles we see in the Inspector's Rotation field - they're actually localEulerAngles.
The best way to limit rotation is to save the initial localEulerAngles in a Vector3 variable and "rotate" the desired angle mathematically:
using UnityEngine;
using System.Collections;
public class CameraController : MonoBehaviour {
public int Sensitivity;
private float MouseY;
private Vector3 CameraAngle;
public GameObject CameraTarget;
void Start () {
CameraAngle = transform.localEulerAngles;
}
void Update () {
// Rotation controls
CameraAngle.x += Input.GetAxis("Mouse Y") * Sensitivity * Time.deltaTime;
CameraAngle.x = Mathf.Clamp(CameraAngle.x, -90, 90);
transform.localEulerAngles = CameraAngle;
}
This code takes care of the rotation control, but doesn't affect position.
In this case the camera Euler angles must be saved into a Vector3 variable. I changed the CameraAngle declaration to Vector3 and used it for that purpose. You can get the current angle in CameraAngle.x.