Thursday, March 21, 2019

12. Event-Driven Input

Under a Node, we have a Label child. Instead of polling in _process for particular input actions, we can use _input to handle input events.


We attach a script to Node, which outputs a string to the label if key is pressed. Had we attached the script to Label, we would either have referred to label.rect_position as self.rect_position or just rect_position. However I believe it more clear to write label.rect_position and attach script to parent.



extends Node

var label
var string

func _ready():
    label = get_node("Label")
    label.rect_position = Vector2(50, 50)

func _input(event):
    if event is InputEventKey:
        string = "Is key pressed: " + str(event.pressed) + "\n"
        string = string + "key: " + str(event.scancode)
        label.set_text(string)

The output, with window size of 200,200, when the spacebar is pressed and held down:


No comments:

Post a Comment