首页 > 解决方案 > Godot - Input.is_action_just_pressed() 运行两次

问题描述

所以我设置了 Q 和 E 来控制固定在 8 个方向上的相机。问题是当我调用 Input.is_action_just_pressed() 时,它设置了两次 true,所以它的内容两次。

这就是它对计数器的作用:

0 0 0 0 1 1 2 2 2 2

我该如何解决?

if Input.is_action_just_pressed("camera_right", true):
    if cardinal_count < cardinal_index.size() - 1:
        cardinal_count += 1
    else:
         cardinal_count = 0
    emit_signal("cardinal_count_changed", cardinal_count)

标签: game-enginegodotgdscript

解决方案


_process_physics_process

_process如果在或中运行,您的代码应该可以正常工作——无需报告两次_physics_process

这是因为如果在当前帧is_action_just_pressed中按下了动作,将会返回。默认情况下,这意味着图形框架,但该方法实际上检测它是在物理框架还是图形框架中被调用,正如您在其源代码中看到的那样。按照设计,每个图形帧只能调用一次,每个物理帧只能调用一次。_process_physics_process


_input

但是,如果您在 中运行代码_input,请记住您将收到_input每个输入事件的调用。并且单个帧中可以有多个。因此,可以有多个_inputwhere调用is_action_just_pressed。那是因为它们在同一个框架中(图形框架,这是默认设置)。


现在,让我们看看建议的解决方案(来自评论):

if event is InputEventKey:
    if Input.is_action_just_pressed("camera_right", true) and not event.is_echo():
        # whatever
        pass

它正在测试是否"camera_right"在当前图形框架中按下了操作。但它可能是当前正在处理的不同输入事件 ( event)。

因此,您可以愚弄这段代码。同时按下配置为的键"camera_right"和其他键(或快到足以在同一帧中),执行将进入那里两次。这是我们试图避免的。

为了正确避免它,您需要检查当前event是否是您感兴趣的操作。您可以使用event.is_action("camera_right"). 现在,你有一个选择。你可以这样做:

if event.is_action("camera_right") and event.is_pressed() and not event.is_echo():
    # whatever
    pass

这就是我的建议。它检查它是否是正确的操作,它是一个按下(不是释放)事件,它不是一个回声(它是键盘重复的形式)。

或者你可以这样做:

if event.is_action("camera_right") and Input.is_action_just_pressed("camera_right", true) and not event.is_echo():
    # whatever
    pass

我不建议这样做,因为:首先,它更长;其次,is_action_just_pressed真的不打算用于_input. 由于is_action_just_pressed与框架的概念有关。的设计is_action_just_pressed旨在与_processor _physics_process, NOT_input一起使用。


推荐阅读