Jack Wilsdon
Jack Wilsdon

Reputation: 7045

Multiple instances of a Texture in LibGDX?

I have a question about speed and efficiency whilst coding a game. I would like to know what the best way would be to have lots of enemies on screen at once. Do I use a single sprite, move it and draw it for every enemy? Or do I have an instance of a Sprite for each Enemy (of which there could be 50 on screen at once). I am wondering about the speed impact of having lots of instances of Sprite (and in turn, Texture). Which of the above would be best for efficiency and overall good practice?

Upvotes: 0

Views: 1514

Answers (1)

bemeyer
bemeyer

Reputation: 6231

Id recommend having an instance of a Sprite for every Monster. All sprites have the same reference to a single texture, so it's easier to have lots of sprites without moving a single texture around.

Here is a example of my code;

public ArrayList<Monster> createMonsters(int count, int maxlevel,
        int minlevel, MonsterTypes type) {
    ArrayList<Monster> monsters = new ArrayList<Monster>();
    // just one texture but multiple sprites
    // save memory :)
    Texture monster = getTextureByType(type);
    for (int i = 0; i < count; i++) {
        // create random level inside the area
        int level = (int) ((Math.random() * maxlevel) + minlevel);
        // create a default monster
        Monster mon = new Monster(level, new Sprite(monster), screen,
                new RandomAI());
        monsters.add(mon);
    }
    return monsters;
}

private Texture getTextureByType(MonsterTypes typ) {
    return this.screen.game.manager.get("monster/" + typ.getFileName()
            + ".png");
}

As you can see it gives every monster a new instance of a sprite with the same texture. All of the sprites refer to the same texture to save memory. Hope this helps.

Upvotes: 3

Related Questions