c# - 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()
被称为每个gametick并且- 它更适合一般检测,例如按键。
然后:
FixedUpdate()
每秒调用 50 次,并且- 它更适合游戏对象转换。
所以如果我的键输入检测在Update()
方法中
if (Input.GetKey(KeyCode.Space))
{
transform.Rotate(Vector3.forward * rotateSpeed * Time.fixedDeltaTime);
}
那么我的轮换代码应该在FixedUpdate()
. 如果是这样,我如何让它在那里运行,同时仍然检测到按键Update()
?
解决方案
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
推荐阅读
- python - 如何对 Pandas 生成的数据透视表进行排序
- karate - 如何从空手道 dsl api 响应中获取相关 ID?
- azure - Azure 密钥保管库基本
- php - 为什么我的流程在执行后会自我复制?该特定进程正在执行两次
- html - SVG 波在 Safari 中未拉伸到 100% 宽度
- ruby-on-rails - Ruby on rails:安装包时验证 SSL 证书的问题
- java - 对象关系映射
- javascript - chrome.webRequest 未定义
- dart - 这个 `^` 运算符在 Dart 中是什么意思?
- r - ggplot 忽略 x 轴因子水平