我目前正在制作飞行模拟器。现在,我正试图让飞机自行飞行,但我在尝试旋转飞机使其与地面平行时遇到了一些问题。
这是我的代码:
heightDetect = new Ray (transform.position, Vector3.down);
if (Physics.Raycast (heightDetect, out hit, Mathf.Infinity)) {
Debug.Log (hit.distance);
transform.rotation = Quaternion.FromToRotation(transform.up, hit.normal) * transform.rotation;
Debug.DrawRay (heightDetect.origin, heightDetect.direction*1000);
}
代码可以正常工作,但问题是它太颠簸了。飞机上的摄像头一直在我的屏幕上晃来晃去,完全无法播放。有没有办法使这个过程顺利进行?谢谢!
最佳答案
大概您在 Update
函数中执行此操作,因此每秒多次更改平面的旋转。您可以使用 spherical linear interpolation 而不是直接设置旋转:
public float speed = 0.1f;
void Update() {
...
var targetRotation = Quaternion.FromToRotation(transform.up, hit.normal) * transform.rotation;
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * speed);
}
这有效地平滑了随时间的旋转。它通过获取当前旋转和最终所需的旋转来工作,但只返回介于两者之间的旋转(由 speed
控制)。
关于c# - Unity - 使用 RayCast 将对象定向到地形 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30452676/