Trouble understanding get_node

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By shaneghoul

I’m having trouble understanding how to use the get_node function, I’ve looked around for an hour or so and haven’t found anything that has helped so I turned to here.
enter image description here

extends KinematicBody2D

func _ready():
    set_fixed_process(true)
    set_pos(Vector2(32, 176)) #Set starting position

func _fixed_process(delta):
    var x = get_pos().x
    var y = get_node("Ball").get_pos().y #Set the Paddle's y to follow the ball's y
    set_pos(Vector2(x, y))

I’m basically just trying to recreate a pong game and the above code is for the computer’s paddle. I’m trying to set it’s y value to always be equal to the y value of the ball however I’m having trouble referencing the ball node as I get the error “Node not found: Ball”. I’m sure I’m missing something obvious but I can’t see it, any help appreciated!

:bust_in_silhouette: Reply From: kidscancode

get_node() is relative to the current node. The Ball node is a sibling of the paddle, so you’d need to use get_node('../Ball') to find it. (As in filesystems .. indicates one level above the current one.

Basically, get_node("..") is equivalent to get_parent()

If you want absolute paths you can do:
get_tree().get_root().get("scene_root_node/foo_node/bar_node
or
get_node("/root/scene_root/blahblah")


ps: As always, I recommend to put the ball on a group and get it when you need it from anywhere in the scene tree instead of hardcoding paths.

eons | 2018-01-30 02:59

It depends which node code file, your get_node() executes in. So had you placed your get_node("Ball") line in the World node code (World.gd) then you would not need relative path.

However because you placed your code in the Ball node (Ball.gd) you need to specifiy get_node("../Ball")

One other item is you can use self. So in your case you could also use var y = self.get_pos().y which would be much cleaner provided your code is within Button.gd

wyattb | 2018-09-17 15:22