Can a child scene "slide" into a parent scene at runtime?

Viewed 114

Is it possible to "slide" a scene (type Control) into the middle of a scene at runtime.

I have a "parent" scene, with a blank area in the middle. I would like to "slide" a sequence of scenes into the central blank area of the parent scene.

I want to do something like this, but with animation:

var qi = load("res://Child1.tscn").instance()
qi.get_node("/root/Child1")
$VBoxContainer/MiddleArea.add_child(qi)

Then later on, slide in the same, or another type of scene, with different or the same data:

var qi = load("res://Child1.tscn").instance()
qi.get_node("/root/Child1")
$VBoxContainer/MiddleArea.add_child(qi)

The sequence is driven by data in a database, so its not predictable at design time what sequence of scenes might need to appear.

1 Answers

If I understand correctly, what you want can be done with a Tween.

So, first off all add Tween to the scene tree. We can hold it in a variable like this:

onready var tween := $Tween

Then we can use it to make a simple animation:

$VBoxContainer/MiddleArea.add_child(qi)

var duration_seconds := 2.0
tween.interpolate_property(
    qi,
    "rect_position",
    Vector2(-qi.rect_size.x, qi.rect_position.y),
    qi.rect_position,
    duration_seconds,
    Tween.TRANS_CUBIC,
    Tween.EASE_OUT
)
tween.start()

This code will animate the position of the scene. The starting position Vector2(-qi.rect_size.x, qi.rect_position.y) is just outside of the screen to the left. And the final position is wherever the scene is positioned before the animation.

If you are adding multiple in a loop at this line to await the end of the animation before doing the next one:

yield(tween, "tween_all_completed")

And if you are adding the scene to a container that is setting the position of the scene, you might want to add it like this:

qi.modulate = Color.transparent
$Container.add_child(qi)
yield(get_tree(), "idle_frame")
qi.self_modulate = Color.white

Here qi.modulate = Color.transparent will make the scene invisible. Then we add it to the container, and wait for one frame with yield(get_tree(), "idle_frame"), during which the container set the position of the scene. And finally we use qi.self_modulate = Color.white to restore the visibility. We have to make the scene invisible so it does not appear for one frame just to disappear and then be animated. And we don't use visible because the container might skip positioning the scene.

Related