Question

Hi I'm making a game platform like. It has background image like a room with doors,items,etc. Now whenever the player try to click on doors or stairs it changes/transition into another background/map.
So what's the best way to do this, performance-wise? I'm planning to make 50 levels, which means 50 different background images.
Should I use array method? or just throw them in the stage and make visible = true whenever transition happens? Or other best way to do it? Thanks all.

Was it helpful?

Solution

What you want to do is store your levels as data somewhere. You do not want to have the objects that belong to all of the levels in existence unless you are actually playing the relevant level. That will result in a large amount of memory consumption and processing power usage, largely used up by objects which aren't even relevant.

The first thing you need to do is decide what data format you want to use to store your level data. XML is very popular because it's quite expressive. I personally use JSON, or in some cases a custom purpose-built format which is a little smaller.

The next thing you need to do is decide what information you want to store in your level data. Typically, you want to store the object types and their positions. Sometimes you might find a need to store extra information - in your case for example, the data for your doors would probably need to have a reference to which level they'll load when you enter them.

Here's an example of what some JSON level data might look like:

{
    id: 1,
    name: 'Level 1',
    objects: [
        { type: 'Wall', x: 20, y: 20 },
        { type: 'Door', x: 40, y: 20, destinationLevel: 2 }
    ]
}

Lastly, you need to architect some classes that digest the data and generate the objects that will make up your level. This might sound confronting at first but actually it's quite straightforward. An example of a simple function that takes level data and generates objects from it might look like this:

function generateLevel(decodedJSON:Object):Array
{
    var levelContent:Array = [];

    for each(var i:Object in decodedJSON.objects)
    {
        var Inst:Class = getDefinitionByName(i.type) as Class;
        var object:Sprite = new Inst();

        object.x = i.x;
        object.y = i.y;

        levelContent.push(object);
    }

    return levelContent;
}

Note: The key here is getDefinitionByName().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top