Is your scene tree unchanged from when you previously asked a question? (i.e., is the Path2D
node still a distinct node that isn’t a child of the player node?)
This code makes use of the _process
method, which is a default method in the Node
class that is called once every frame. If you manually change the position of the Path2D
in the editor and press F5 on the keyboard (or F6, or click the ‘play’ button), _process
will get called and snap the Path2D
to a position that’s 20 pixels above the player’s position.
distance
can be changed in multiple ways. One of them is via a signal. Because the player
and Path2D
nodes are separate and don’t have a parent/child relationship, you could make a “message bus” to communicate between them.
First, make a new script and name it message_bus.gd
. Open your project settings menu (project->project settings
at the top of your screen.) Make the newly created script an autoload (go to ‘globals’, click on the folder icon, select the script, then click ‘add’.)
Now edit the script. Add the following code to it:
class_name MessageBus
@warning_ignore("unused_signal")
signal set_new_offset(offset : float)
Save the script. Now in Path2D
’s script, add the following:
func _ready(_delta : float)->void:
MessageBus.set_new_offset.connect(change_offset.bind())
func change_offset(offset : float)->void:
distance = offset
The class MessageBus
defines a signal that takes one float as a parameter. _ready
in the Path2D
script is called after the scene and its children enter the tree, and it connects method change_offset
to the signal so that whenever the signal is emitted, change_offset
is called.
You can now emit the signal from anywhere you please (I assume in your player script somewhere) using this line of code:
MessageBus.set_new_offset.emit(whatever_new_value_you_want)
Where whatever_new_value_you_want
is a float, and your desired offset.