如何解决玩家在 Unity 中的 Update() 中移动,但不是 FixedUpdate()
我制作了一个统一的汽车控制器来开车。我读过 FixedUpdate 更适合用于物理对象而不是 Update,但是当我切换到 FixedUpdate 时,我的汽车不再行驶。有谁知道为什么会这样?非常感谢您提供的任何帮助!
public float speed;
public float turnSpeed;
private RigidBody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
Move();
Turn();
}
void Move(){
// moves the car
if (Input.GetKey(KeyCode.W)){
rb.AddRelativeForce(new Vector3(Vector3.forward.x,Vector3.forward.z) * speed);
}
else if (Input.GetKey(KeyCode.S)){
rb.AddRelativeForce(new Vector3(Vector3.forward.x,Vector3.forward.z) * -speed);
}
// maintains forward veLocity relative to car.
Vector3 localVeLocity = transform.InverseTransformDirection(rb.veLocity);
localVeLocity.x = 0;
rb.veLocity = transform.TransformDirection(localVeLocity);
}
void Turn(){
// turns the car.
if (Input.GetKey(KeyCode.D)){
rb.AddRelativetorque(Vector3.up * turnSpeed);
Debug.Log("TURNING CAR");
}
else if (Input.GetKey(KeyCode.A)){
rb.AddRelativetorque(-Vector3.up * turnSpeed);
Debug.Log("TURNING CAR");
}
这是代码。按 W 或 S 会增加一个力,按 A 或 D 会增加扭矩。当我尝试打开 FixedUpdate 时,控制台会写出“TURNING CAR”,因为它应该显示它正在通过 AddRelativetorque 线,但它仍然不会转动,所以我不确定发生了什么。再次感谢,非常感谢您的帮助。
解决方法
尝试增加使用的力。
固定更新的运行频率低于更新(在大多数情况下使用默认设置)。由于代码的运行频率要低得多,因此在同一时间段内积累的力也更少。
考虑一个以 100fps 运行的游戏。默认的固定时间步长为 0.02 秒(每秒 50 帧)。由于更新以 100fps 运行,因此更新所施加的力是固定更新所施加的力的两倍。
如果您使力值与自上次更新以来的时间无关,则无需担心这一点。
更新使用 myForceValue * Time.deltaTime。
对于 FixedUpdate 使用 myForceValue * Time.fixedDeltaTime。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。