Godot进行2D游戏开发入门-按键事件

2023-08-08 12:57:40 浏览数 (1)

项目设置事件

您可以在下面设置输入地图 项目> 项目设置 > 输入映射 然后这样做:

每一帧判断事件

代码语言:javascript复制
# 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

按键事件回调触发

代码语言:javascript复制
# input event - runs when the input happens
func _input(event):
    if event.is_action_pressed("jump"):
        jump()

按键事件

代码语言:javascript复制
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")

鼠标事件

鼠标按钮

代码语言:javascript复制
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")

鼠标移动

下面是一个使用鼠标事件拖放 Sprite 节点:

代码语言:javascript复制
extends Node

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

视区显示坐标

使用节点中的函数获取鼠标坐标和视区大小,例如:

代码语言:javascript复制
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)

或者,可以向视区询问鼠标位置:

代码语言:javascript复制
get_viewport().get_mouse_position()

设置鼠标光标

代码语言:javascript复制
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)

0 人点赞