如何解决如何在 Y 上钳制四元数?
后来也到了两边,但现在在 Y 上。
using UnityEngine;
using System;
using System.Collections;
public class RotationTest : MonoBehaviour
{
public Transform target;
public Transform objToRotate;
void LateUpdate()
{
Vector3 relativePos = target.position - objToRotate.position;
Quaternion rotation = Quaternion.LookRotation(relativePos,Vector3.up);
rotation.y = Mathf.Clamp(rotation.y,-1f,1f);
objToRotate.rotation = rotation;
}
}
我尝试过:
rotation.y = Mathf.Clamp(rotation.y,1f);
但它不起作用我也尝试了值 -50f 和 50f
解决方法
Quaternion
有 四个 分量,x,y,z,w
并且它们都在 -1,1
范围内移动 .. 所以你的夹紧绝对没用;)
=> 切勿直接接触 Quaternion
的组件,除非您真的很清楚自己在做什么!
在您的情况下,您似乎想限制它围绕给定轴旋转的角度(在您的情况下为 Vector3.up),因此您可以使用的是 Quaternion.ToAngleAxis
,限制该角度并将其转换回使用 Quaternion.AngleAxis
旋转,例如
Quaternion rotation = Quaternion.LookRotation(relativePos,Vector3.up);
// Extract the axis and angle
rotation.ToAngleAxis (out var angle,out var axis);
// Since ToAngleAxis returns only unsigned angle
// this checks if we actually have a negative rotation
if(angle > 180)
{
angle -= 360;
}
// Clamp the angle to the desired limits
angle = Mathf.Clamp(angle,-50,50);
// Finally convert both back to a rotation
transform.rotation = Quaternion.AngleAxis(angle,axis);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。