简体   繁体   中英

Clamp a quaternion rotation in unity

I have this code but I have not been able to find a decent solution to clamp the X axis between 2 angle values. How would it be done in this case?

public class CameraController : MonoBehaviour {
    public float cameraSmoothness = 5f;

    private Quaternion targetGlobalRotation;
    private Quaternion targetLocalRotation = Quaternion.Identity;

    private void Start(){
        targetGlobalRotation = transform.rotation;
    }

    private void Update(){
        targetGlobalRotation *= Quaternion.Euler(
            Vector3.up * Input.GetAxis("Mouse X"));
        
        targetLocalRotation *= Quaternion.Euler(
            Vector3.right * -Input.GetAxis("Mouse Y"));

        transform.rotation = Quaternion.Lerp(
            transform.rotation,
            targetGlobalRotation * targetLocalRotation,
            cameraSmoothness * Time.deltaTime);
    }
}

For this you would rather use Euler angles and only convert them to Quaternion after applying the clamp!

Never directly touch individual components of a Quaternion unless you really know exactly what you are doing! A Quaternion has four components x , y , z and w and they all move in the range -1 to 1 so what you tried makes little sense ;)

It could be something like eg

// Adjust via Inspector
public float minXRotation = 10;
public float maxXRotation = 90;

// Also adjust via Inspector
public Vector2 sensitivity = Vector2.one;

private float targetYRotation;
private float targetXRotation;

private void Update()
{
    targetYRotation += Input.GetAxis("Mouse X")) * sensitivity.x;      
    targetXRotation -= Input.GetAxis("Mouse Y")) * sensitivity.y;

    targetXRotation = Mathf.Clamp(targetXRotation, minXRotation, maxXRotation);

    var targetRotation = Quaternion.Euler(Vector3.up * targetYRotation) * Quaternion.Euler(Vector3.right * targetXRotation);

    transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, cameraSmoothness * Time.deltaTime);
}

You need to Clamp Mouse Y + transform.rotation.x like this

    float v = Input.GetAxis("Mouse Y") * -_verticalSensitive;
    float x = _camera.transform.rotation.x;
    float r = Mathf.Clamp(x + v, -0.5f, 0.5f) - x;
    _camera.transform.Rotate(r, 0, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM