Godot Engine输入系统详解:键盘、鼠标与触摸处理
输入系统架构概述
Godot Engine的输入系统通过统一的接口处理各类输入设备,核心实现位于core/input/input.h和core/input/input_event.h。该系统采用事件驱动模型,支持键盘、鼠标、触摸、游戏手柄等多种输入设备,并提供跨平台的一致性体验。
核心组件关系
键盘输入处理
按键事件类型
Godot通过InputEventKey类处理键盘输入,支持物理按键码、标签按键码双重识别方式:
- 物理按键码:基于键盘硬件布局的按键标识
- 标签按键码:基于按键语义功能的标识(如
Key::ENTER始终对应回车键)
关键API在core/input/input.h中定义:
bool is_key_pressed(Key p_keycode) const;
bool is_physical_key_pressed(Key p_keycode) const;
bool is_key_label_pressed(Key p_keycode) const;
实践示例:检测按键状态
# 检测空格键是否按下
if Input.is_key_pressed(Key.SPACE):
print("空格键被按住")
# 检测Ctrl+C组合键(跨平台兼容)
if Input.is_key_pressed(Key.CONTROL) and Input.is_key_pressed(Key.C):
print("复制快捷键被触发")
鼠标输入处理
鼠标模式控制
Godot提供多种鼠标显示模式,定义在core/input/input.h#L50-L57:
| 模式 | 描述 |
|---|---|
| MOUSE_MODE_VISIBLE | 可见(默认) |
| MOUSE_MODE_HIDDEN | 隐藏光标 |
| MOUSE_MODE_CAPTURED | 捕获光标(用于第一人称游戏) |
| MOUSE_MODE_CONFINED | 限制在窗口内 |
| MOUSE_MODE_CONFINED_HIDDEN | 限制并隐藏 |
设置鼠标模式示例:
# 设置为捕获模式(如第一人称游戏)
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
# 恢复可见模式
Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)
鼠标事件处理
鼠标事件包括按钮事件和移动事件,分别由InputEventMouseButton和InputEventMouseMotion处理:
func _input(event):
# 鼠标移动事件
if event is InputEventMouseMotion:
print("鼠标移动: ", event.relative)
# 鼠标按钮事件
if event is InputEventMouseButton:
if event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
print("左键点击位置: ", event.position)
触摸输入处理
触摸事件类型
移动设备触摸输入通过以下类处理:
InputEventScreenTouch:触摸开始/结束事件InputEventScreenDrag:触摸滑动事件
核心属性包括触摸点索引、位置和相对移动,定义在core/input/input_event.h#L383-L464。
单点触摸示例
func _input(event):
# 触摸开始
if event is InputEventScreenTouch and event.pressed:
print("触摸开始 - 索引: ", event.index, " 位置: ", event.position)
# 触摸滑动
if event is InputEventScreenDrag:
print("触摸滑动 - 索引: ", event.index, " 移动: ", event.relative)
多点触摸支持
Godot天然支持多点触摸,通过index属性区分不同触摸点:
var active_touches = {}
func _input(event):
if event is InputEventScreenTouch:
if event.pressed:
active_touches[event.index] = event.position
else:
active_touches.erase(event.index)
print("当前活动触摸点: ", active_touches.size())
高级输入特性
输入映射系统
Godot允许通过项目设置定义输入动作,将多个输入源映射到同一游戏功能:
- 在项目设置中添加动作(如"move_forward")
- 关联多个输入事件(如W键、上箭头键、手柄左摇杆上推)
- 在代码中通过动作名检测输入:
if Input.is_action_pressed("move_forward"):
velocity += transform.basis.z * -speed
输入事件传播流程
输入事件在场景树中自顶向下传播,可通过accept_event()停止传播:
func _input(event):
if event.is_action_pressed("ui_cancel"):
hide_menu()
event.accept_event() # 阻止事件继续向下传播
跨平台适配
Godot输入系统自动处理不同平台的输入特性:
- 桌面平台:完整支持键盘、鼠标、游戏手柄
- 移动平台:触摸输入、加速度计、多点触摸
- 主机平台:专用手柄支持(需编译对应平台版本)
性能优化建议
- 事件过滤:在
_input(event)中优先检查事件类型再处理 - 使用输入动作:减少硬编码按键,提高代码可维护性
- 批量处理:对于高频事件(如鼠标移动),考虑在
_process()中批量处理
# 优化鼠标移动处理
func _process(delta):
if Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED:
mouse_delta = Input.get_last_mouse_velocity()
rotate_y(deg_to_rad(-mouse_delta.x * sensitivity))
更多输入系统细节可参考:
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考




