C# 在轴上固定方向
我有一个第一人称刚体胶囊,它可以旋转,这样他就可以一直垂直于重力方向。我想将我的播放机旋转到一边,这样播放机摄像头就不会垂直旋转 我的密码是C# 在轴上固定方向,c#,unity3d,C#,Unity3d,我有一个第一人称刚体胶囊,它可以旋转,这样他就可以一直垂直于重力方向。我想将我的播放机旋转到一边,这样播放机摄像头就不会垂直旋转 我的密码是 void Update() { FixOrientation(); } void FixOrientation() { if (trans.up != -GetGravityDirection()) { Quaternion targetRotation = Quaternion.FromToRotation(tr
void Update() {
FixOrientation();
}
void FixOrientation()
{
if (trans.up != -GetGravityDirection())
{
Quaternion targetRotation = Quaternion.FromToRotation(trans.up, -GetGravityDirection()) * trans.localRotation;
trans.localRotation = Quaternion.RotateTowards(trans.localRotation, targetRotation, 5f);
}
}
结果是,,
在上图中,我将重力方向改为指向天花板
此代码仅在全局x轴上旋转玩家,无论他面向何处,这意味着当我面向全局向前或向后时,玩家将垂直旋转摄影机。我想要的是它在局部z轴上旋转。Unity已经有了一个精确的方法:有一个角度的重载和一个旋转轴 可能看起来像
// rotation speed in degrees per second
public float RotationSpeed;
void Update()
{
FixOrientation();
}
void FixOrientation()
{
if (transform.up != -GetGravityDirection())
{
// Get the current angle between the up axis and your negative gravity vector
var difference = Vector3.Angle(transform.up, -GetGravityDirection());
// This simply assures you don't overshoot and rotate more than required
// to avoid a back-forward loop
// also use Time.deltaTime for a frame-independent rotation speed
var maxStep = Mathf.Min(difference, RotationSpeed * Time.deltaTime);
// you only want ot rotate around local Z axis
// Space.Self makes sure you use the local axis
transform.Rotate(0, 0, maxStep, Space.Self);
}
}
旁注:
一般来说,要注意两个向量的直接比较
trans.up != -GetGravityDirection()
使用近似值0.00001。在你的情况下,这应该是好的,但为了比较,你应该使用
Vector3.Angle(vector1, vector2) > threshold
要定义更宽或更强的阈值我仍然存在一个问题,即第一人称相机可以在y轴上旋转播放器,如果在应用FixOrientation时使用该相机,会产生不希望的循环旋转,但这足以回答问题。谢谢。很高兴它能帮助您!我还注意到,当方向不完全是Vector3.up或-Vector3.up时,它可能仍然会超调,导致闪烁。但奇怪的是,如果同时改变y轴,它的行为会有所不同,但这可能来自于计算差异的方式