在 FixedUpdate 上使用 Input.GetKey() 真的错了吗? [英] Is it really wrong to use Input.GetKey() on FixedUpdate?

查看:35
本文介绍了在 FixedUpdate 上使用 Input.GetKey() 真的错了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道有一个规则",Input 函数不应该在 FixedUpdate() 中使用;如果我们这样做,Input.GetKeyDown() 可能不起作用,但是使用 Input.GetKey() 真的有错吗?

We know there's a "rule" that Input functions shouldn't be used inside the FixedUpdate(); Input.GetKeyDown() may not work if we do so, but is it really wrong to use Input.GetKey()?

假设我们想要在以某种不依赖于硬件性能的速率按住某个键时触发某些东西.我不想创建一个逻辑来使用增量时间或在 Update 中编写关键检测代码并在 FixedUpdate 中触发代码来控制它.

Let's say we want to fire something when pressing and holding a key at some rate that is not dependent on hardware performance. I don't want to create a logic to control this using delta time or writing key detection code in Update and firing code in FixedUpdate.

FixedUpdate 中做所有事情没有意义吗?会发生什么 - 我们可能会丢失一些按键事件,这些事件无论如何我们都不想要,以保持我们想要的速率.

Doesn't make sense to just do everything inside FixedUpdate? What can happen - we may lose some key pressed events, the ones that we didn't want anyway, to keep our desired rate.

但是如果发生了一个关键事件,我们会失去它吗?Update 后是否有重置,所以我们不会在 FixedUpdate 上看到它?

But what if one single key event happens, can we lose it? Is there a reset after Update, so we won't see it on FixedUpdate?

推荐答案

来自 GetKeyDown 文档:

您需要从 Update 函数中调用此函数,因为状态每帧重置

You need to call this function from the Update function, since the state gets reset each frame

所以是的,输入状态每帧都会重置,这意味着硬件会产生影响,具体取决于 UpdateFixedUpdate 之间触发的频率.

So yes, the Input state is reset each frame meaning hardware will have an effect depending on how frequently Update fires between FixedUpdate.

确实没有一种简单的方法可以避免创建由 FixedUpdate 使用的 Input 的副本,但我建议重新评估您的逻辑以将内容移入 Update.

There really isn't an easy way to avoid creating a copy of the Input that is used by FixedUpdate, though I would suggest reevaluating your logic to move things in to Update.

更新:

关于下面 Rutter 的评论.我只是注意到 OP 正在询问 GetKey(),我写的关于 GetKeyDown() 的内容对于 GetKey() 仍然适用,尽管文档没有' 不明确这么说.

Regarding Rutter's comment below. I just noticed the OP was asking about GetKey(), what I wrote about GetKeyDown() remains true for GetKey() though the documentation doesn't explicitly say so.

这可以通过进入时间管理器和将 FixedUpdate 速率更改为一些长间隔,例如 1 秒.然后执行以下操作:

This can be verified by going in to the Time Manager and changing the FixedUpdate rate to some long interval like 1 second. Then do something like:

void FixedUpdate() {
    if(Input.GetKey(KeyCode.D)){
        Debug.Log("D-Key Down");
    } else {
        Debug.Log("No key down");
    }
}

如果您在 1 秒固定帧之间按下并释放D",您将只会看到No Key Down".

If you press and release 'D' between the 1 second fixed frames you will only see "No Key Down".

这篇关于在 FixedUpdate 上使用 Input.GetKey() 真的错了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆