如何解决在unity3d中使用刚体的最佳导航代码?
我想按一次键
我的立方体向右移动并旋转90度
轮换做得很好
但是它不能很好地移动
having
解决方法
您的主要问题是:您应该仅在FixedUpdate
中进行与物理相关的操作,例如Rigidbody
的运动。
对于协程,Unity提供了WaitForFixedUpdate
的名称,它确实按照名称所说,确保在FixedUpdate
物理调用中执行了代码。
private IEnumerator RotatePlayer(Vector3 byAngle,Vector3 dir,float inTime)
{
yield return new WaitForFixedUpdate();
// here I would also use "rig" instead of "transform"
Quaternion fromAngle = contactPoint.transform.rotation;
Quaternion toAngle = Quaternion.Euler(rig.eulerAngles - byAngle);
for (float t = 0; t < 1; t += Time.deltaTime / inTime)
{
yield return new WaitForFixedUpdate();
// here I would also use "rig" instead of "transform"
rig.MovePosition(rig.position + (dir * speed * Time.deltaTime));
rig.MoveRotation(Quaternion.Slerp(fromAngle,toAngle,t));
}
}
此外,您还不清楚您确切定义为not move well
的含义。您还应该以某种方式确保一次仅运行一个例程。通过终止已经运行的例程,例如
private void Update()
{
if (Input.GetKeyDown(KeyCode.D))
{
StopAllCoroutines();
StartCoroutine(RotatePlayer(Vector3.forward * 90,Vector3.right,time));
}
if (Input.GetKeyDown(KeyCode.A))
{
StopAllCoroutines();
StartCoroutine(RotatePlayer(Vector3.back * 90,Vector3.left,time));
}
}
或使用类似的标志
阻止新例程开始运行,直到当前例程结束为止private bool alreadyRotating;
private IEnumerator RotatePlayer(Vector3 byAngle,float inTime)
{
if(alreadyRotating) yield break;
alreadyRotating = true;
......
alreadyRotating = false;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。