Android Popping Bubbles Example
This example is a bit simpler than the bouncing ball demo I posted ten days ago. When you tap the screen, a bubble appears. This bubble grows until it pops. Tapping several times makes several bubbles.
Android Bubbles Example from Eric Burke on Vimeo.
Goals:
- Animate many different objects. In this case, growing circles. There is only one background thread running the “game loop”. It keeps a list of circle positions and sizes. You could easily apply this same concept to any kind of animation.
- Play a popping sound when each bubble pops.
The pop sounds like crap on the phone, even worse in the video. You can find the original popping sound on freesound.org. I clipped the sound (using Audacity) to make it play faster, I suspect it can be improved with some work.
You can find the source code for BubblesModel.java and BubblesActivity.java on GitHub.
This app still has a serious bug, described in this Android Developer’s Post. Let me know if you know how to fix this!
Aside from that bug, this is not production-ready code. It is pretty sloppy with memory, copying a List of Bubble objects on each iteration of the game loop. I opted for brute force synchronization just to make it work. For a real game, I’d spend more time on fine-tuned locking and sharing objects to minimize garbage collection.
I am not an Android guy but let me put some comments regarding the synchronization that you added in the model object.
I guess you can completely remove the synchronization of model’s collection object by using another trick. If I understood correctly, following is the code snippet that demands the need for synchronization on model’s bubble collection.
if (event.getAction() == MotionEvent.ACTION_DOWN) {
model.addBubble(event.getX(), event.getY());
return true;
}
Instead of adding bubble in the async: onTouch callback, add the eventX and eventY to a synchronized eventqueue. Then poll and clear this queue and subsequently add bubbles in the gameloop. In this way, we can safely remove all the synchronization that you put in the model class. Sync is still there but only for the eventqueue. We access them only in a serial fashion with in the gameloop.
Try to do such a serial access to MediaPlayer also.
Basic idea is simple. Stay away from concurrent modification to shared data structure but store the callback related events and access them in a serial way in the gameloop. Its little bit tricky but I have successfully applied for j2me.