# polling - runs every frame func _physics_process(delta): if Input.is_action_pressed("ui_right"): # move as long as the key/button is pressed position.x += speed * delta
按键事件回调触发
1 2 3 4
# input event - runs when the input happens func _input(event): if event.is_action_pressed("jump"): jump()
按键事件
1 2 3 4 5 6
func _unhandled_input(event): if event is InputEventKey: if event.pressed and event.keycode == KEY_J: AudioManager.play("pistol") if event.pressed and event.keycode == KEY_K: AudioManager.play("laser_gun")
鼠标事件
鼠标按钮
1 2 3 4 5 6
func _input(event): if event is InputEventMouseButton: if event.button_index == BUTTON_LEFT and event.pressed: print("Left button was clicked at ", event.position) if event.button_index == BUTTON_WHEEL_UP and event.pressed: print("Wheel up")
var dragging = false var click_radius = 32# Size of the sprite
func _input(event): if event is InputEventMouseButton and event.button_index == BUTTON_LEFT: if (event.position - $Sprite.position).length() < click_radius: # Start dragging if the click is on the sprite. if !dragging and event.pressed: dragging = true # Stop dragging if the button is released. if dragging and !event.pressed: dragging = false
if event is InputEventMouseMotion and dragging: # While dragging, move the sprite with the mouse. $Sprite.position = event.position
视区显示坐标
使用节点中的函数获取鼠标坐标和视区大小,例如:
1 2 3 4 5 6 7 8 9
func _input(event): # Mouse in viewport coordinates if event is InputEventMouseButton: print("Mouse Click/Unclick at: ", event.position) elif event is InputEventMouseMotion: print("Mouse Motion at: ", event.position)
# Print the size of the viewport print("Viewport Resolution is: ", get_viewport_rect().size)
或者,可以向视区询问鼠标位置:
1
get_viewport().get_mouse_position()
设置鼠标光标
1 2 3 4 5 6 7 8 9 10 11 12 13
extends Node
# Load the custom images for the mouse cursor. var arrow = load("res://arrow.png") var beam = load("res://beam.png")
func _ready(): # Changes only the arrow shape of the cursor. # This is similar to changing it in the project settings. Input.set_custom_mouse_cursor(arrow)
# Changes a specific shape of the cursor (here, the I-beam shape). Input.set_custom_mouse_cursor(beam, Input.CURSOR_IBEAM)