Wednesday, March 20, 2019

7. Position2D node

Position2D can be used to set reference points. We attach 2 reference points to a sprite (one offset north west and the other south east). The sprite (icon.png) is 64 by 64. Thus, the offsets set in the inspector are (-32,-32) and (32,32).


Like everything in programming there are many ways of doing the same thing. The advantage of this node is that it is seen as a crosshair in the editor. With Godot, you should be familiar of changing things both graphically and with code.


We use the following nodes:



In the top-most node, Player (an Area2D node), we attach this script, which prints the two reference points as we move the sprite:



extends Area2D

var sprite
var pos
var pos_nw
var pos_se

func _ready():
    sprite = get_node("sprite")
    sprite.position = Vector2(100, 100)
    pos_nw = sprite.get_node("pos_nw")
    pos_se = sprite.get_node("pos_se")
    var pos_nw_loc = pos_nw.get_global_position()
    var pos_se_loc = pos_se.get_global_position()
    print("Initial pos_nw_loc = " + str(pos_nw_loc))
    print("Initial pos_se_loc = " + str(pos_se_loc))

func _process(delta):
    var change = 0
    pos = Vector2(0, 0)
    if Input.is_action_pressed('ui_left'):
        pos.x = -1
        change = 1
    elif Input.is_action_pressed('ui_right'):
        pos.x = 1
        change = 1
    elif Input.is_action_pressed('ui_up'):
        pos.y = -1
        change = 1
    elif Input.is_action_pressed('ui_down'):
        pos.y = 1
        change = 1
    if change == 1:
        var pos_nw_loc = pos_nw.get_global_position()
        var pos_se_loc = pos_se.get_global_position()
        print("pos_nw_loc = " + str(pos_nw_loc))
        print("pos_se_loc = " + str(pos_se_loc))
    sprite.position += pos

The output, with window size of 200,200:


No comments:

Post a Comment