首页 > 解决方案 > Update() 和 FixedUpdate() 之间有什么区别,应该如何将这些区别应用于控制运动?

问题描述

这是我处理游戏对象的简单玩家移动的代码。它允许用户上下左右移动对象,并启用旋转。

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed = 10f;
    public float rotateSpeed = 10f;

    public Rigidbody2D rb;
    Vector2 movement;

    void Update()
    {
        movement.x = Input.GetAxis("Horizontal");
        movement.y = Input.GetAxis("Vertical");

        if (Input.GetKey(KeyCode.Space))
        {
            transform.Rotate(Vector3.forward * rotateSpeed * Time.fixedDeltaTime);
        }
    }

    void FixedUpdate()
    {
        rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
    }
}

我的印象是:

然后:

所以如果我的键输入检测在Update()方法中

if (Input.GetKey(KeyCode.Space))
{
    transform.Rotate(Vector3.forward * rotateSpeed * Time.fixedDeltaTime);
}

那么我的轮换代码应该在FixedUpdate(). 如果是这样,我如何让它在那里运行,同时仍然检测到按键Update()

标签: c#unity3d

解决方案


FixedUpdate用于与物理系统同步。在向RigidBody施加力(或在您的情况下为MovePosition)时,您将使用FixedUpdate

至于您的Rotate,您应该在Update中进行。这将为您提供下一个渲染帧的最准确位置(即使在下一帧之前多次调用Update )。此外,您应该在更新计算中使用Time.deltaTime 。像这样:

transform.Rotate(Vector3.forward * rotateSpeed * Time.deltaTime);

Time.fixedDeltaTime用于FixedUpdate

参考:https ://docs.unity3d.com/ScriptReference/MonoBehaviour.FixedUpdate.html


推荐阅读