在 Godot 中,有两个主要工具处理玩家的输入:
- 内置的输入回调,主要是
_unhandled_input(),和_process()一样,也是一个内置的虚函数,Godot 每次在玩家按下一个键时都会调用 Input单例,单例是一个全局可访问的对象,Godot 在脚本中提供对几个对象的访问,它是每一帧检查输入的有效工具
func _process(delta: float):
var direction = 0
if Input.is_action_pressed("ui_left"):
direction = -1
if Input.is_action_pressed("ui_right"):
direction = 1
rotation += angular_speed * direction * delta
使用 Input 进行 if 判断,调用 Input.is_action_pressed() 检查玩家按下某个键,使用字符串表示一个输入动作,该按键被按下时返回 true ,其他时候返回 false
这里对应的就是响应左右两个方向按键

1、按“上”时移动

添加了对于“上”的事件响应
var velocity = Vector2.ZERO
if Input.is_action_pressed("ui_up"):
velocity = Vector2.UP.rotated(rotation) * speed
2、完整脚本
extends Sprite2D
var speed = 400
var angular_speed = PI
func _process(delta: float):
var direction = 0
if Input.is_action_pressed("ui_left"):
direction = -1
if Input.is_action_pressed("ui_right"):
direction = 1
rotation += angular_speed * direction * delta
var velocity = Vector2.ZERO
if Input.is_action_pressed("ui_up"):
velocity = Vector2.UP.rotated(rotation) * speed
position += velocity * delta
Godot中的每个脚本都代表一个类,并扩展了引擎的一个内置类