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!

- 103
- 1
- 8
-
Take a look at the stage actor system. It does already implement a "stage" where you add all actors. with a simple .draw of the stage it does draw every actor at its current position and its current state. You can take a look into the code of it to understand the system. May also take a look at the gameloop concept. – bemeyer Dec 09 '13 at 10:39
-
1Great suggestion mind=blown benn! – TypingTurtle Dec 10 '13 at 05:47
1 Answers
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.

- 10,301
- 1
- 32
- 28