Unity触碰函数OnTriggerStay与Input.GetKeyDown

发布时间 2023-03-29 18:21:16作者: Relolihentai

(写写博客尝尝鲜)

触碰函数中不要使用按键检测

我想让玩家在某个区域内进行按键检测,代码如下

 1 void TriggerPlayerStay(Collider2D collider)
 2     {
 3         if (collider.CompareTag("Player"))
 4         {
 5             if (Input.GetKeyDown(KeyCode.Z))
 6             {
 7                 Door.SetActive(true);
 8             }
 9         }
10     }

但经常Z键按烂了也没用

因为触碰函数在物理时钟周期上运行,按键检测一定要写在帧周期内,也就是Update函数中

如下:

 1 void TriggerPlayerStay(Collider2D collider)
 2     {
 3         if (collider.CompareTag("Player"))
 4         {
 5             isStay = true;
 6         }
 7     }
 8 private void Update()
 9     {
10         if (isStay)
11         {
12             if (Input.GetKeyDown(KeyCode.Z))
13             {
14                 Door.SetActive(true);
15             }
16         }
17     }