LibGDX Sprite Batching and adding in new sprites at runtime

413 views Asked by At

I am a new programmer working with the libgdx engine and was wondering about the act of sprite batching. specifically how to add sprites to the batch for drawing during a programs lifecycle. so far all examples of sprites have used some code similar to: batch.begin(); sprite.draw(batch); batch.end(); etc. and it is unclear to me how i would draw a varied number of sprites since each sprites .draw must be called in the batch... thank you in advance for the explanation!

1

There are 1 answers

0
R Hyde On

In simple terms, think of each call to sprite.draw() as a request to draw the sprite at some point. Each call to sprite.draw() adds the sprite to the batch. When batch.end() is called, all of the sprites added to the batch will be drawn and the batch will be emptied. As the contents of the batch are not persistent (ie, it is emptied when batch.end() is called) so sprites and images must be added to it each time it is used.

In the following example, all sprites to be drawn are stored in a collection of sprites and are added to the batch each time it is drawn, which is on each and every frame if it is being called from a render() method.

batch.begin();
for (sprite : sprites) {
    sprite.draw(batch);
}
batch.end()

The reality is a little more complicated, as the sprite batch will flush when it is full and under a few more circumstances, but a good rule of thumb is to add everything that you want to draw on each and every frame.