Problems with transform when instantiating AnimatableBody2D

Godot Version

4.5

Question

I have a small system in place to spawn levels in ‘chunks’ within a main scene. These chunks are scenes of themselves and are spawned at Marker2D nodes.

The problem I am encountering is that most nodes within the chunks instantiate at the right coordinates (relative to the placed Marker2D). However, AnimatableBody2D nodes will always spawn relative to the 0,0 coordinates of the main scene. This will not happen if I turn off ‘sync to physics’.

So I know that something is ‘overriding’ the transform for the AnimatableBody2D in relation to the chunks root node transform. I’m suspecting it has something to do with the fact that transform is an integral part of the AnimatableBody2D’s setup and that the physics step is performed before or after the instantiating, causing the problem. Is there a way to fix this without having to unsync from physics?

Hope someone can help. Much appreciated.

Make sure you haven’t accidentally enabled top_level flag.

I don’t think this is the issue. The problem persists even with a ‘fresh’ AnimatableBody2D node where nothing is set different than default.
Or am I misunderstanding what you mean?

1 Like

Right. Can you show the structure of your scene and all the code running after the scene has been instantiated.

Here is the scene structure:

The following script is attached to ChunkContainer:

extends Node2D

@export var chunk_scene: PackedScene
@onready var chunk_container: Node2D = $"."
@onready var chunk_load_marker: Marker2D = $"../ChunkLoadMarker"

func _ready() -> void:
	_spawn_first_chunk()

func _spawn_first_chunk() -> void:
	if not chunk_scene:
		print("No chunk scene assigned")
		return

	var chunk_instance: Node2D = chunk_scene.instantiate()
	chunk_container.add_child(chunk_instance)

	var chunk_start_marker: Marker2D = chunk_instance.get_node("ChunkStartMarker")
	var offset_y = chunk_load_marker.global_position.y - chunk_start_marker.global_position.y
	chunk_instance.global_position.y += offset_y

	# This in combination with manually turning off 'Sync to physics' seems to 'solve' the issue.
	for body in chunk_instance.get_children():
		_sync_animatable_bodies(body)

	print("Chunk spawned at Y:", chunk_instance.global_position.y)


func _sync_animatable_bodies(node: Node) -> void:
	if node is AnimatableBody2D:
		node.reset_physics_interpolation()
	for child in node.get_children():
		_sync_animatable_bodies(child)```

The chunk scene as well, and all _ready() scripts that run inside it.

Could this be the cause of your issue?