LibGDX – Demos Updated for LibGDX 1.2.0
After some prompting I have finally got around to updating my LibGDX extenstion library and associated demos. The core library has been modified to pull the LibGDX library from the default maven repository at version 1.2.0. The demos have been updated accordingly to match the adjusted API. You can find all it in the usual place here.
Update
The poms for the Android targets were not correct. I have updated them. To install type:
mvn -Pandroid install
LibGDX – Simple Shooter Demo Broken (update – fixed)
I seem to have somehow cocked up a commit to the LibGDX demos and deleted some asset files for the Simple Shooter demo. My apologies to anyone trying to build this. The really bad thing is that I thought I had backups in my own subversion repository and to my horror it isn’t there at all so I am going to have to put the missing fonts and stuff together again which isn’t going to be quick. I’ll put a notice up when it’s fixed. Sorry about this.
Update
Okay, I have fixed it. As noted in the comments I did look at the version history but it seems I may not have committed the files properly in the first place. Pretty lax of me not to check a fresh build out on my most popular github repo but I hopefully have learned my lesson. I am going to make sure I have a back up to my local SVN as well in future.
One last note is that the Android maven build seems to be broken still so I am going to look at that next.
LibGDX: Noiz2-gdx Vector Shoot Em Up
I have been noticing that there are quite a few instances of my original port of Kento Chos esoteric shooter – Noiz2 available. It has made it’s way across the internet on various app stores mostly unchanged which is fine by me. A few people have added adverts. Good luck to them.
Anyway, just to keep ahead of the game a bit I thought it was time to lavish some love on the noiz2 codebase and see if I couldn’t bring something new to the party. With this in mind I have mavenized it, ported it over to use LibGDX and put it up on Github. This took most of this weekend but I think I have almost got there.
The main new additions are:
- Mavenized (hurray)
- Moving star background
- Minor tweaks to the GFX.
- Much nicer menu with a lot borrowed from the Simple Shooter demo.
It is not finished. I have not wired the preferences or the persistence of what levels the player has completed. Also the Android platform hasn’t been added yet.
The most interesting thing about the porting procedure was that it was pretty painless. I had abstracted the graphics and control elements previously as I had OpenGL and Canvas renderers available for the Android version. Wiring in the GDX elements was a complete doddle.
Future improvements
- Rewrite the ScreenGDX primitive renderer to be more efficient (I have yet to try this on Android).
- Proper glowing vector lines.
- Saving game state.
- Saving preferences.
Code is here.
Update #1
I have got persistence of the game state and some of the original setting like sound and volume working with the LibGDX ‘Preferences’ class. Not so hard after all. The settings screen is a little flaky though. I have also started to tidy up a lot of the game text which was a bit wonky looking. One thing to note is I have ditched the original bitmap logo as I just don’t think it looked very good. I am trying to improve the look and feel overall rather than go for a ‘classic’ port of the game. I have, after all, already done that.
Update ‘#2
Added a nice menu. Can’t get it to run on Android yet.
Update #3
Working on Android. Looks good. Persistence of settings not working properly. I plan to fix this and then publish as an update.
LibGDX: Demos on Github
I have made a start on fully Mavenizing my LibGDX demos and placed them up on Github.
The good news is that the core netthreads-libgdx library and the demos have been converted to use the latest version of LibGDX (0.9.9 at the time of writing). Taking the latest build from the LibGDX repo should mean that it will be easier to keep these up to date with changes to Scene2d etc.
I used the LibGDX archetype so you should have no problems building these once you have jumped through a few (minor I hope) hoops to install some dependencies on non-maven-available jar files like the tween-engine and fixtureatlas. There are detailed instructions. If you are having problems make a comment/email me or raise an issue on the issues list.
The core library is here. You will need this for the demos.
The demos up so far are:
Simple Shooter
This is the same simple shmup as before but with a lot of code tidied up. It is here.
Menu
Main
Box2d-Test
A straightforward Box2d demo with a central rotating fixture, falling objects and nice fading labels. It is here.
Box2d-Bumpers
Bumper walls, anti-gravity, tumbling blocks and flashing psychedelics..what’s not to like? Shows how to detect collisions between box2d elements and how to handle them.
Putting these all the once place I have discovered a ton of bugs which I have had a chance to go through and fix. Later demos fixed stuff which I never went back and applied to the earlier ones like SimpleShooter so this has been a great exercise. It’s even given me a bit of a kick to write some more.
NOTE: All the LibGDX demos linked on this blog go to GitHub now. It is easier to manage them all in the one place. The new demos have a bunch of new concepts in them like the removal of the old Singleton patterns with Google Guice managing this stuff instead. Also it’s Maven from here on. If you are familiar with the old code and build mechanism then you’ll just have to come along for the ride. I promise you’ll learn stuff that will benefit you.
LibGDX:Audio – Tonome OSC version
Ah sweet synthesized music! Here is a screenshot of my Tonome LibGDX application sending OSC Bundle messages to a instance of pure data. The pure data instance is broadcasting the OSC Bundle contents as Midi note out messages to a bank of Crystal synths running inside Podium. Each VST synth instance has been assigned a different Midi channel where each channel is associated with a different panel on the Tonome application. Neat!
This has been my project for the last couple of weeks.
I am going to tidy up the code somewhat and publish this next. I’ll expand a bit on the implementation as well. There is all sorts of stuff in the code like my own java OSC implementation, netty, pure data and google Guice would you believe.
LIBGDX – Demos Update to 0.9.6
I have finally updated all the LibGDX demos to the latest release version of LibGDX as of today (0.9.6).
Here are the links
Tonome – A tonematrix style sample player here.
Box2D with Scene2D – Bumpers demo here.
Box2D with Scene2D – Simple fixture demo here.
Game Test – Simple shoot-em-up with settings panel and slide transitions here.
The update was fairly painless with a few things to note:
- LibGDX 0.9.6 now deals correctly with the ‘finish’ method and actions. The ‘finish’ method is now called on every associated action when an actor is marked for removal. This is important as the overridden ‘finish’ is where we put our actions back into the appropriate pools. Prior to this fix I was having to sub-class actor to implement this myself.
- The tween engine has been updated also to version 6.3.3. The only change I had to make was alter the callback mechanism. I still can’t see a way to re-initialise a composited tween but I need to investigate further .
- I note there is event management in the yet unpublished version of Scene2d. This promises to be interesting but it’s not in 0.9.6 which is what we are using here. I am not going to go near any of that stuff until a proper release is made.
Some of the demos have a maven pom file.Technically these are purely for illustration as they don’t pull the libGDX files from any repository just locally. I use them to generate the project files for the maven style layout (resources directory etc).
Note
These demos have all been updated, mavenized and are now up on Github. There has been a ton of fixes and improvements.
LibGDX – Audio – Tonome
Tonome is an matrix style sample player in the same vein as Tonematrix and Monome. This version is the result of a lot of attempts to get something which is usable. I think this is close but not quite there yet but I’m going to release the code as I’m tired of playing around with it and want to leave it for a while.
Source code here.
You can get a flavour of what’s involved from these screenshots below.
Features include:
- Multiple panels with a nice sliding transition between them including a new diagonal transition.
- Matrix buttons with a toggle action so that as you slide over the buttons you are either setting or clearing. The buttons will also flash as the assigned sound is being played.
- Bar display to show which bar is currently being played.
- Touch buttons to navigate between panels which are animated to flash along to the bar display.
I couldn’t decided on how to present the settings for volume and BPM so I have placed them into a fairly boring setting view for the moment. There should be some kind of slide in panel which has these on the main interface but I’ll put that off for the moment. You can exit the touch panels by ESC on PC and the ‘back’ key on the phone.
The assigned samples are fixed for the moment as this is still technically a demo/prototype. You can see in the code where they are inserted if you want to change them.
I have only tried this in the emulator for the moment as my Nexus phone won’t talk to my PC anymore 🙁 The android project is bundled with the source. The emulator gives me a laughable 4fps which is unusable so there may be an issue with running it on a real phone. If it works can someone tell me.
Note Choice
I studied tonematrix to see what notes the application used as they have been chosen specifically to go together. These are A3,B3,D3,E3,G3,A4,B4,D4..and so on.
Sample Choice
I spent ages trawling freesound to try and get some decent samples that sounded good together. I can’t say I have succeeded. This stuff is hard. I went through a ton of them before selecting the final choice. I’m still unhappy with how they sound. A future plan is to forego samples altogether and instead have OSC support but in the meantime the samples demonstrate the intention of how to build up a composition from the different panels. There are two panels with ‘lead’ type sounds, one bass panel and one drum machine panel with some nice samples from a TR909.
There is a subtlety in the sample choice which I should point out as you are bound to notice it. The samples on the second (right) panel appear to play together in polyphony okay. There is always going to be a slight delay in the launching of each sample but if your lucky it shouldn’t be noticeable. The samples on the first panel, on the other hand, don’t seem to sit so well together once you start to bunch them up on the same bar. For the first 4 notes on my PC it plays fine but thereafter increasing the number of simultaneous notes makes a scratching sound appear. I am convinced this is something to do with the sample itself as the other samples don’t exhibit this behaviour. If I get a chance I will try and fix this somehow. You can always insert your own samples. If you get some decent ones and want to share then drop me a line.
OSC Support
I think there the core of a nice control panel for audio here. It would require proper message support for OSC messages but should be doable. I haven’t managed to find a suitable OSC library (with the appropriate license) yet but I will keep looking.
Re-pitching Audio Samples
I tried to use SoundTouch to re-pitch a selected audio sample but could only get it to work on the desktop version as I put together a kind of hacky solution.
- Loading the base sample and re-pitching.
- Creating a WAV file sample image with the re-pitched data in memory.
- Creating a Sound class but hi-jacking the file load to pull the data from my in-memory WAV file image.
This actually worked really well but only for the Desktop since Android uses SoundPool to manage audio samples. You can find the code in a class called “AudioHelper”. As I say it never made the final cut but might prove useful if you are targeting a desktop application only.
Source code here. As usual Apache 2.0 license.
Update #1
I am in the process of implementing OSC support. When I get this working the plan is to show how to hook the panel up to MIDI. I’ll probably drop the sample playing aspect if this as well as make the UI look a bit nicer.
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.
LibGDX: Scene2D with Box2D
Here is another LibGDX demo. This one uses Box2D to build a simple model of a box with a gear cog spinning in the centre. If you click on the screen a ball is released which will drop into the view and bounce off the gear and walls. I am no expert in Box2D but I think you may find this useful if you are trying to combine it and LibGDX Scene2D elements.
This demo is heavily indebted to the ideas from the demo provided for the Box2D editor which I used to create the polygon model for the central cog.
Few things of note to point out:
- Each body in the world has an associated Actor sprite. I am using an Action to map the position and rotation of each body to the linked Actor. The conversion from Box2D position to pixels is by a conversion factor (the pixel width / the Box2D world width).
- Bodies loaded from the Box2D editor have their position-origin on the bottom left corner. The bodies created from the Box2D ‘primitives’ are positioned at their centre. Handling this inconsistency is a bit of a pain and makes the code a lot less elegant.
- When you close the view (select the BACK key for Android or ESC for Windows) the world is not destroyed, only the balls are marked for removal and subsequent clean-up. When you close the application it will re-claim the memory used.
- There is actually two demos in the source. Under the ‘test’ package you will find a view which uses the LibGDX Box2D debug renderer. You kind of need this to build a ‘world’ before trying to map Scene2D elements to it.
- When you click on the screen fading text is displayed with the pixel co-ordinates. This is just for fun and to show off the sort of things you can do with actions.
Here is a screenshot of the debug rendered ‘world’.
The demo code is licensed under the same license as LibGDX itself with Apache 2.0.
Demo code here.
LibGDX: Scene2D demo with Scene Transitions
Anyone familiar with Cocos2d will recognise the concept of Scene transitions. These are classes which compose an incoming and outgoing scene and apply an effect to them to a transition from one to the other.
I have updated my simple demo to apply slide-in scene transitions using the magic of the Java Universal Tween Engine (although I guess I could have used the stock actions). They use the TimeLineAction class I built in the previous demo to run two seperate TimeLines on the incoming and outgoing scenes (stages). I am quite pleased how elegant the code has turned out to be for these. The “settings” and “about” screens have bounce applied to them as they ease-out which gives a nice effect.
Implementation
First we define the base class which composes the two scenes and runs the in and out actions on the contents of the composed scenes. We don’t have to manually clean up any actions because we will always let them run until they are “done”.
public class TransitionScene extends Scene implements TweenCallback { private boolean complete; private float inX; private float inY; private float outX; private float outY; private Scene inScene; private Scene outScene; private Group inSceneRoot; private Group outSceneRoot; private int durationMillis; private TweenEquation easeEquation; /** * Enter handler makes a note of scene contents position. * */ @Override public void enter() { this.complete = false; inX = inSceneRoot.x; inY = inSceneRoot.y; outX = outSceneRoot.x; outY = outSceneRoot.y; } /** * Exit handler resets scene contents positions. * */ @Override public void exit() { this.complete = true; inSceneRoot.x = inX; inSceneRoot.y = inY; outSceneRoot.x = outX; outSceneRoot.y = outY; } /** * Draw both scenes as we animated contents. * */ @Override public void draw() { // Move inSceneRoot.act(Gdx.graphics.getDeltaTime()); outSceneRoot.act(Gdx.graphics.getDeltaTime()); // Draw if (!complete) { outScene.draw(); } inScene.draw(); } /** * Default transition handlers */ @Override public void onEvent(EventType eventType, BaseTween source) { switch (eventType) { case COMPLETE: Director.instance().setScene(this.inScene); break; default: break; } } /** * Transition complete. * * @return The transition complete handler. */ public boolean isComplete() { return complete; } }
So an actual transition class like “MoveInRTransitionScene” (Move In From the Right) looks like this below.
public class MoveInRTransitionScene extends TransitionScene { private static Pool _pool = new Pool() { @Override protected MoveInRTransitionScene newObject() { MoveInRTransitionScene transitionScene = new MoveInRTransitionScene(); return transitionScene; } }; /** * Create transition. * * @param inScene * The incoming scene. * @param outScene * The outgoing scene. * @param durationMillis * The duration of transition. * @param easeEquation * The easing type. */ public static MoveInRTransitionScene $(Scene inScene, Scene outScene, int durationMillis, TweenEquation easeEquation) { MoveInRTransitionScene transitionScene = _pool.obtain(); transitionScene.setInScene(inScene); transitionScene.setInSceneRoot(inScene.getRoot()); transitionScene.setOutScene(outScene); transitionScene.setOutSceneRoot(outScene.getRoot()); transitionScene.setDurationMillis(durationMillis); transitionScene.setEaseEquation(easeEquation); return transitionScene; } /** * On entry build easing TimeLines. * */ @Override public void enter() { super.enter(); // In Scene TimeLine. Timeline inTimeline = Timeline.createSequence() .beginSequence() .push(Tween.to(getInSceneRoot(), GroupAccessor.POSITION_XY, 0).target(getInScene().width(), 0).ease(getEaseEquation())) .push(Tween.to(getInSceneRoot(), GroupAccessor.POSITION_XY, getDurationMillis()).target(0, 0).ease(getEaseEquation())) .end() .start(); // In Scene TimeLine Action. TimelineAction inTimelineAction = TimelineAction.$(inTimeline); getInSceneRoot().action(inTimelineAction); // Out Scene TimeLine. Timeline outTimeline = Timeline.createSequence() .beginSequence() .push(Tween.to(getOutSceneRoot(), GroupAccessor.POSITION_XY, 0).target(0, 0).ease(getEaseEquation())) .push(Tween.to(getOutSceneRoot(), GroupAccessor.POSITION_XY, getDurationMillis()).target(-getOutScene().width(), 0).ease(getEaseEquation())) .addCallback(EventType.COMPLETE, this) .end() .start(); // Out Scene TimeLine Action. TimelineAction outTimelineAction = TimelineAction.$(outTimeline); getOutSceneRoot().action(outTimelineAction); } /** * On exit tidy up. * */ @Override public void exit() { super.exit(); _pool.free(this); } }
Some stuff to note here.
- I am applying the trick of initialising the TimeLine by applying a tween of duration zero.
- I am using a pool and cleaning it up in the node enter and exit methods. These methods are very similar to their counterparts in Cocos2d .
- It is actually possible to draw multiple stages in this fashion which was a bit of an experiment and somewhat of a pleasant surprise when I tried it.
Usage
To actually use the transition you give references to the incoming and outgoing scenes along with duration and easing type. The transitions are pooled so they can be reused.
private void transitionToSettingsScene() { Scene inScene = getSettingsScene(); Scene outScene = this.director.getScene(); TransitionScene transitionScene = MoveInLTransitionScene.$(inScene, outScene, DURATION_SETTINGS_TRANSITION, Bounce.OUT); this.director.setScene(transitionScene); }
I have tidied a great deal of the code up but there are still a few funnies hanging around.
- The LED font looks terrible on the Android emulator. My Nexus phone won’t talk to my Windows 7 machine since I had to replace the USB cable (never lend your phone to anyone) so I have no idea what this looks like on an actual phone. BTW this font is not free for commercial use. I am going to find one which is and replace it.
- The ship rotation sometimes gets confused. Needs investigated.
The demo now has all of the features that were in my original example using my own framework. I am going to concentrate on fixing the above issues next.
Demo code here. The code is licensed under the same license as LibGDX itself with Apache 2.0.
Update #2
There was an issue with the first version of the code. It was leaking objects. I have fixed this and made some improvements to the life-cycle of the sprites.
Update #3
In the process of looking at something else I realised I was creating multiple instances of the SpriteBatch object by having Scene subclass from Stage. I have fixed this and added disposal of the batch contents on cleanup from the controller.