Need help with referencing a node

Godot Version

4.1

Question

I need to reference a Characterbody2d (Body) in a script in a other Characterbody2d (fist).
I am trying to reference Body in fist’s script so that I can aquire its position for the fist to use for its target I want it to constantly follow.

Please help me, I’ve been stuck on this issue for half a week and am desperate for a solution

Don’t set initialize variables to things that won’t be ready instantly.

You could prepend @onready to some variables, but in this case it would be best to use the _ready function

@export var body: CharacterBody2D
var target: Vector2

func _ready() -> void:
    target = body.position + Vector2(90, 45)

But then you’ll find that Vector2 is a copied value, not referenced, so it does not update after being set. You want to use body.position directly, as body is referenced.

if position .x > body.position.x + 90:

Make sure to paste code instead of a screenshot

```
type or paste code here
```

1 Like

Not Sure if i understand the issue correctly, but I’m assuming you want to know the position of body?

if that’s the case you can drag and (while holding ctrl) drop the body into the fist.gd code which should look something like this

@onready var player = $"../Player"

and then you use in this example “player” as reference.

i did this

@onready var player = $"../Player"


func get_transform():
	var col = player.get_global_transform()
	print(col)

which prints
[X: (1, 0), Y: (0, 1), O: (417.9335, -27.0673)]

there is most likely a better way but hope this helped

thank you so much

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.