Tuesday, March 19, 2019

5. Input

For the Sprite in Example 4, we use Input to keep checking whether we are pressing an arrow key.


If so, we move in that direction by changing the sprite.position member variable, which it inherits from Node2D.


The screen size, is 200 by 200 and sprite initial position is the center (100, 100).


We have to do the movement code in the game loop in the _process function.



extends Node

var pos
var sprite = Sprite.new()

func _ready():
    sprite.texture = load("res://icon.png")
    sprite.position = Vector2(100, 100)
    add_child(sprite)

func _process(delta):
    pos = Vector2(0,0)
    if Input.is_action_pressed('ui_left'):
        pos.x = -1
    elif Input.is_action_pressed('ui_right'):
        pos.x = 1
    elif Input.is_action_pressed('ui_up'):
        pos.y = -1
    elif Input.is_action_pressed('ui_down'):
        pos.y = 1
    sprite.position += pos 

The output after the sprite is moved to top left:


No comments:

Post a Comment