问题描述
我制作了一个统一的汽车控制器来开车。我读过 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。