我有一个第一人称刚体胶囊,旋转,这样他将永远垂直于重力方向。我想把我的播放器旋转到一边,这样玩家的相机就不会垂直旋转。
我的代码是,
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轴)。
发布于 2018-10-25 05:40:27
统一已经有了一种精确的方法:Transform.Rotate有一个过载的角度和一个旋转轴。
可能看上去像
// 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定义更宽或更强的阈值
https://stackoverflow.com/questions/52981463
复制相似问题