+1 vote

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.

asked Apr 12 in Engine by Sreenington (18 points)

1 Answer

0 votes
Best answer

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.

answered Apr 12 by njamster (8,990 points)
selected Apr 12 by Sreenington

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?

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.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.