LibGDX : Scene2D – Box2d – Bumpers Demo
This demo encapsulates some of the Scene2D and Box2D integration I have been playing around with. Specifically collision detection and selection by touch/mouse.
Below is a screenshot with random numbered elements bouncing around inside the view. The walls are supposed to act like pinball bumpers so that when an element hits them they give the element a ‘kick’. The implementation for this is pretty experimental but seems to work well enough for illustration.
I have implemented a layer which lets you ‘grab’ an element body. When picked up a selection animation is run around the selected element (the zooming white square). The selection mechanism is actually completely generalised in the sense that it broadcasts events which another layer responds to for the animation. Nice and loosely coupled.
When an element hits the wall it will bounce and make a clonk sound but when hits another element it will run a flashing animation at the points where the bodies touch and play a boing sound. This illustrates I am detecting what sort of collision is taking place. The layer which has the bouncing elements also has a pool of contact listeners which it can dish out to elements in the view. They are released from the pool when an element is removed (by clicking on it).
There is some neat stuff here (at least I think so).
- Separate ‘netthreads’ LibGDX extension library which gathers together most (but not all) of the scene, layer, action and event handling classes I have written to support my approach to the design of these demos so far. There is a pom for generating the library as a Maven component although it’s not used as such here. Note it pulls the LibGDX libraries as scope “system”.
- Gravity update Action which gives bodies in the World lighter than air behaviour.
- Body update Action as seen in the previous demo which maps a Box2D body to a Scene2D Actor.
- Walls to enclose the World.
- Contact listener elements which implement ‘bumper’ behaviour to the Box2D World walls.
- Touch Layer which decouples the selecting of bodies in the view through the use of the event pipeline.
- Pointer Layer which implements a nice ‘selection’ animation around the selected Actor when touched. Try grabbing one of the rolling numbers with your mouse and you will see what I mean.
- Clonk sounds for hitting the walls and a satisfying boinging sound for when elements hit each other.
These features will hopefully find their way into an actual application at some point. I have a whole load of bits and pieces which are slowly coalescing into something.
I haven’t created the Android wrapper for this. It’s trivial to put this together and it saves me using my webspace which I am starting to fill at an alarming rate.
Demo code here.
There is a test application bundled as well which uses the LibGDX debug renderer.
This uses LibGDX 0.9.3.
All the code is licensed as Apache 2.0.