Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

c# - 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);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 e.g.

// 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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...