When using a TextureAtlas to create a Sprite with the createSprite method, the LibGDX documentation says: This method uses string comparison to find the region and constructs a new sprite, so the result should be cached rather than calling this method multiple times.
How do I cache these results? Is it just a variable I create to store the created sprite? If so then how do I create different copies of the same sprite?
Each time you use the createSprite
method, a new Sprite
gets created. Usually you'd have one sprite per enemy for example. Let's say that you have a class Frog
which is one of your enemies. It should look like this (pseudo-code):
public class Frog {
private Sprite sprite;
public Frog(TextureAtlas atlas) {
sprite = atlas.createSprite("frog");
}
public void update(float deltaTime) {
// update the sprite position
}
public void render(Batch batch) {
sprite.draw(batch);
}
}
Now each Frog
would have its own Sprite
. This is necessary, since all frogs can be in different places. The position will be configured via the Sprite
. You will create the sprite just once in the constructor and all of those sprites share the same TextureRegion
of the same TextureAtlas
, which will result in a good performance, since there won't be many texture switches on the graphics card, when you render your frogs.