问题描述
我们知道有一个规则",即不应在FixedUpdate()
内部使用Input
函数; 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
文档:
所以,是的,每个帧都会重置输入状态,这意味着硬件会根据FixedUpdate
在FixedUpdate
之间触发的频率而起作用.
So yes, the Input state is reset each frame meaning hardware will have an effect depending on how frequently Update
fires between FixedUpdate
.
虽然我建议您重新评估将内容移入Update
的逻辑,但确实没有一种简单的方法来避免创建由FixedUpdate使用的Input的副本.
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()
的问题,尽管有关文档未明确说明,但我为GetKey()
撰写的有关GetKeyDown()
的内容仍然适用.
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",则只会看到无键按下".
If you press and release 'D' between the 1 second fixed frames you will only see "No Key Down".
这篇关于在FixedUpdate上使用Input.GetKey()真的错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!