What is the best approach to swap between areas in a game?


(Linck) #1

I need to have some areas, and each of this area has a trigger. When the player collides with the trigger, he goes to a different area.

So lets suppose there is area A, B and C. The player is in area A. When he touches a trigger, he needs to be transported to area B. But also in area A there was another trigger that would transport him to area C.

Also, I think the areas should be entities, not worlds, because they share the same UI.

How would you structure this?

I’m asking because my ways of doing this always seem to be over complicated, and cause memory leaks. So I’m asking for some ideas.


(Jacob Albano) #2

What do you mean when you say “the areas should be Entities”? To me, that sounds like a perfect fit for a World. Entities can’t contain other entities, and that’s what you want to do.

If you need to share a UI between all of your worlds, you can do that pretty easily by sharing a single entity between all worlds that need it. Here’s an example:

// all of your areas should extend this world class
public class Area extends World
{
    public static var UI:UserInterface = new UserInterface();
    
    public function Area()
    {
        super();
    }

    // called when this becomes the active world
    override public function begin():void
    {
        add(UI);
    }

    // called when this is no longer the active world
    override public function end():void
    {
        remove(UI);
    }
}

When you extend Area , each area you have will share the same UI instance, keeping its data persistant as you travel through the game.

As far as triggers go, you could do this:

public class Trigger extends Entity
{
    private var nextWorld:Class;

    public function Trigger(nextWorld:Class)
    {
        this.nextWorld = nextWorld;
    }

    override public function update():void
    {
        if (triggered)
        {
            FP.world = new nextWorld();
        }
    }
}

(Linck) #3

But then if I want the images from the previous world to be deleted from memory I have to call some method or it does automatically?


(Jacob Albano) #4

It will happen automatically as long as they aren’t being used anymore.


(Linck) #5

Thanks a lot @jacobalbano, I have redone my code so areas are worlds and It seems to be working nicely. There is no memory leak and it turns out it seems to be more reasonable too.

Also, I’m actually not calling remove or recycle for any of my entities in the end method, because it looks like they are being removed automatically anyway.