[英]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.我有这段代码,但我无法找到一个合适的解决方案来将 X 轴夹在两个角度值之间。 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!为此,您宁愿使用欧拉角,并在应用夹具后才将它们转换为
Quaternion
!
Never directly touch individual components of a Quaternion
unless you really know exactly what you are doing!永远不要直接接触
Quaternion
各个组成部分,除非您真的很清楚自己在做什么! 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 ;) Quaternion
有四个分量x
、 y
、 z
和w
,它们都在-1
到1
的范围内移动,因此您尝试的方法毫无意义;)
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你需要像这样夹住鼠标 Y + transform.rotation.x
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.