I just can NOT get the distance to things working, it’s not really about the distance at this point, its about finding the nodes. I just cant find them???
Also i am kinda new to coding so it might just be a dumb mistake
var player_position = %player.global_transform.origin
var item_position = %testitem.global_transform.origin
just doesnt work for some reason
Godot Version
4.3
(also yes i tried it without the %, idk how it really works…)
Your error makes it clear that the root cause of your issue is due to an invalid object reference ('null instance').
Are you absolutely sure that your code uses the correct name of the nodes, and that the reference is valid at runtime?
EDIT: I know what your issue is. Since your variables are defined outside of any virtual function (e.g. _ready()) the tree is not yet built so you can’t get a reference to the objects unless you annotate the variables with @onready (see GDScript reference). That should fix it!
Hmm… it seems you need to study how and when a program/script is executed.
Your variable definitions (for those defined in the scope of the class) are initialized and updated only when an instance of that class is created. When @onready is added to a variable definition, it’s the same as assigning a value to the variable in _ready() – it’s only done once.
If you wish to continuously update a variable, you have to make use of a consistently executing loop. In the case of Godot, you may use _process() to do this every frame.
You’re updating the distance but not the values used to compute it.
I would recommend defining player_position, item_position, and distance in the scope of _process() instead. You don’t need to remember the information from one frame to the next, therefore, no need to store it outside the function.
func _process(_delta: float):
var player_pos = %player.global_position
var item_pos = %testitem.global_position
var distance = player_pos.distance_to(item_pos)
# Your code...
You’re being too fast and rash in your corrections. Slow down and think for a second. Read through what I’ve said and research what you don’t understand.
Where is item_pos and player_pos defined; you don’t seem to be defining them in _process() so where are they?
I’ll tell you what. Make a new topic so someone else will help you. No one is going to look at this topic since it’s solved already.
You barely have any idea of how to write code and what everything means. There are so many things that I could start to check for you but that becomes really tiring. You need to learn the language of coding. It’s like talking to someone who barely knows English – it’s exhausting.