July 4, 2012

Java & Candy

Eye candy, to be precise.
Who said that all Java games look cheap and amateurish ? With the help of OpenGL you have all possibilities of modern graphics hardware at your hands.

So I decided to polish Biodrone Battle a bit by adding dynamic particle effects for explosions and other game events. The game uses LibGDX as OpenGL frontend. Setting up particles is pretty easy and for tweaking the appearance there is a nice graphical editor available.

Each particle effect is made from one or more particle emitters, defined in plain text files. Additionally, an image file (a small filled circle, e.g.) is named which is used to actually draw each particle. If no image path is specified, just place the image into the same folder as the particle definitions.

First, you load the definitions:

FileHandle particleFolder = Gdx.files.classpath("resource");
FileHandle smokeParticleFile = Gdx.files.classpath("resource/smoke.particles");

ParticleEffect effect = new ParticleEffect();
effect.load(smokeParticleFile, particleFolder);

To render the particles, you need to start once, then position, update and draw the emitters:

effect.setPosition(x, y);
effect.draw(batch, ds);

Updating is done in each game frame by supplying a valid SpriteBatch and a time delta (in seconds). Naturally, you can also reposition the emitters for getting moved particles. To do so, the attached property must have been enabled in the particle definition file.
Furthermore, particle emitters can run either once or continously. This is decided by the continuous property. To check whether a one-time emitter is done, call isComplete().

Loading and parsing of the definitions files does not need to be done each and every time again during the game loop. A ParticleEffect can act as template to create cloned objects from which are then actually drawn:

ParticleEffect effectTemplate = ...
ParticleEffect effect = new ParticleEffect(effectTemplate);

When cleaning up, only the templates need to be disposed because the internal textures are shared between all clones.

Fun stuff :)