What is the best system to manage scene/level changing

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Sreenington

Currently, I do scene changing by detecting if a player collides with a Portal block, then change the scene on the path defined.

extends Area2D
func _physics_process(_delta):
var bodies = get_overlapping_bodies()
print(bodies)
for body in bodies:
	if body.name == "Player":
		SceneChanger.change_scene("res://test.scn")

The “SceneChanger” is a singleton which takes in a path and animates(a simple fade in fade out).

A problem arises that there is only one ‘Portal Collison Block’ but I want multiple, which each teleports the player into a different location in different scenes. How can I accomplish this?
I had an idea where I define each teleport block as an enum and each has a path to different scenes. But how can I define a scene path on enums(I’m very new to GDscript, sorry) and make so that when a player collides with a particular code block, the system will be able to identify which portal it is and where it is supposed to send the player.

:bust_in_silhouette: Reply From: njamster

You can use an export-variable for that, i.e. a variable in your script that’s exposed to the inspector, thus can be set for each instance individually.

extends Area2D

export (PackedScene) var change_to

func _physics_process(_delta):
    var bodies = get_overlapping_bodies()
    print(bodies)
    for body in bodies:
        if body.name == "Player":
            SceneChanger.change_scene(change_to)

Add multiple instances of your portal block, select each of them individually in the tree and set the change_to-property in the Inspector to the scene, you want the portal to teleport the player to. You might also consider connecting to the body_entered-signal of the Area2D instead of actively polling for overlapping bodies each frame:

extends Area2D

export (PackedScene) var change_to

func _on_Area2D_body_entered(body):
    if body.name == "Player":
        SceneChanger.change_scene(change_to)

If you never connected a signal before, take a look here.

Screenshot

As shown above, a particular world scene has 3 collision areas(Portals) which each teleports to 3 different scenes.

extends Area2D

export (PackedScene) var Room1
export (PackedScene) var Room2
export (PackedScene) var Room3

After setting the path in Inspector for each, how can I detect collision in each of the collision areas separately?

Sreenington | 2020-04-12 17:04

Simply create one instance of your Area2D for each portal in the room. They will share the same code (the one I provided above), but each instance can be positioned individually and assigned a custom room scene to teleport to.

njamster | 2020-04-12 17:12