Confusion with global_position and odd setting behaviour

Godot Version

4.3

Question

I have encountered some weirdness when I try and set my objects global_position which has led to two questions. I have the following two chunks of code for spawning a scene and positioning it in my game which output the scenes global_position and then the instantiated scenes global position:

	# Code 1:
	print("my global position is " + str(global_position))
	var projectile = spawnedWoodChunk.instantiate() as RigidBody3D
	var pos: Vector3 = global_position
	pos.y = 3.0
	projectile.global_position = pos
	print("projectile global position is " + str(projectile.global_position))
    # Code 1 output:
    my global position is (-4.68938, -1, 8.45854)
    projectile global position is (0, 0, 0)

The result of code 1 is that my projectile is spawned in a completely unexpected location; some distance from the spawner depending on how close to the origin I am. If I set pos to Vector(0.0, 3.0, 0.0) the spawn location is where I expect.

	# Code 2:
	print("my global position is " + str(global_position))
	var projectile = spawnedWoodChunk.instantiate() as RigidBody3D
	projectile.global_position = global_position
	projectile.global_position.y = 3.0
	print("projectile global position is " + str(projectile.global_position))
    # Code 2 output:
    my global position is (-4.68938, -1, 8.45854)
    projectile global position is (0, 0, 0)

The result of code 2 is that my projectile spawns exactly where I expect; at the location of the spawner with y = 3.

Three questions:

  1. Why does the second print in both cases print a zero vector and not the vector I assigned to projectile.global_position?
  2. Why do these two code snippets produce different results in where the projectile is spawned? I can see no functional difference between the two.
  3. Setting global_position appears to be relative to the object and not actually global as the name suggests. For example if global_position is Vector3(1, 1, 1) and I set the projectiles global_position as Vector3(1, 1, 1) then it’s actual global position seems to become Vector3(2, 2, 2). Is this correct?

Could it be that you have to add the projectile to the world (add_child(proyectile)) to show you its real position?

capitanlopez is right.

Nodes have to be in the scene tree to make global_position work correctly.

get_tree().root.add_child(node) or as a child to another scene (you might set top level = true for the childs transform in that case to avoid moving it with the parent, for example for projectiles).

Thanks all. It appears you are correct. Adding to the scene first then setting the position or adding it to the root scene both worked. Thanks for the suggestions. Strange behaviour nonetheless.