+2 votes

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!

in Engine by (17 points)

1 Answer

+5 votes
Best answer

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.

by (21,712 points)
selected by

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.

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.