Input Handling
本技能针对 Godot 游戏开发中的输入处理,提供键盘、鼠标、手柄与触摸输入的专业模式,并包含缓冲与可访问性支持。
可用脚本
- input_buffer.gd:用于响应式控制的输入缓冲,将动作缓冲 150ms 以保证紧凑的游戏手感。
- input_remapper:运行时输入重绑定,支持冲突检测与存档/读档持久化。
强制要求——响应式控制:在实现跳跃/冲刺机制前,先阅读 input_buffer.gd。
输入处理中的禁止事项
- 绝不在 _process() 中轮询输入用于游戏玩法动作——应使用 _physics_process() 或 _unhandled_input()。_process() 依赖帧率,低 FPS 时会导致输入丢失。
- 绝不使用硬编码按键检查(KEY_W、KEY_SPACE)——应使用 InputMap 动作。硬编码按键无法重绑定,且在非 QWERTY 键盘上会失效。
- 绝不忽略手柄死区——0.05 幅度的摇杆漂移会导致角色自行移动。务必使用 0.15-0.2 死区的 Input.get_axis()。
- 绝不假设单一输入设备——玩家可能在会话中途从键盘切换到手柄。监听 Input.joy_connection_changed 并动态更新 UI 提示。
- 绝不将 _input() 用于游戏玩法动作——_input() 会对所有事件触发(包括 UI)。应使用 _unhandled_input(),仅在 UI 未消费事件时触发。
- 绝不忘记响应式控制的输入缓冲——玩家在落地前 50ms 按下跳跃?没有缓冲,跳跃会丢失。为紧凑游戏手感缓冲输入 100-150ms。
InputMap 动作
设置:项目设置 → 输入映射 → 添加动作
# 检查动作是否在本帧按下
if Input.is_action_just_pressed("jump"):
jump()
# 检查动作是否持续按住
if Input.is_action_pressed("fire"):
shoot()
# 检查动作是否释放
if Input.is_action_just_released("jump"):
release_jump()
# 获取轴(-1 到 1)
var direction := Input.get_axis("move_left", "move_right")
# 获取向量
var input_vector := Input.get_vector("left", "right", "up", "down")
InputEvent 处理
func _input(event: InputEvent) -> void:
if event is InputEventKey:
if event.keycode == KEY_ESCAPE and event.pressed:
pause_game()
if event is InputEventMouseButton:
if event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
click_position = event.position
手柄支持
# 检测手柄连接
func _ready() -> void:
Input.joy_connection_changed.connect(_on_joy_connection_changed)
func _on_joy_connection_changed(device: int, connected: bool) -> void:
if connected:
print("Controller ", device, " connected")
参考
Godot 文档:InputEvent