Tuesday, December 30, 2008

Skeletal Animation with XNA

My Bad
Well, I am still working on skeletal animation. I was able to find out that skeletal animation is supported in the .x and .fbx model file formats. However, it is not directly supported by either the DirectX or XNA API's. But there is a demo application that shows you the code necessary to load an animated model file containing bones and keyframed animations (the keyframes are only manipulating the bones, in a skeletal animation file).

So, what do you know I bought a book:

update: there is a newer version of the book out for XNA 3.0. I haven't picked it up yet to see whats new or changed but you may want to start with that if your interested in skeletal animation in XNA.

Thought it might be a little helpful to unravelling the mysteries of skeletal animation in XNA. So far it has been pretty much just a straight forward rip off of the demos from the XNA community site. With perhaps a small smidgen of useful detail on how the code works and what things you need to do to get it working.

The book uses three separate projects although for a Microsoft developer whats another project. To an indie, it's a lot of overhead you don't need especially if you are only going to have two or three classes in each project. Another set of endlessly nested project configuration settings and adding project references. Although, bringing them in under a single solution could work to mitigate the risk of wasting too much time hopping between instances of Visual Studios and making sure your using the latest compiled version of the libraries.

But I am guessing once I have it all working I won't have to touch it again for a long while. Provided there are no problems loading the exported model files.

Saturday, December 13, 2008

XNA Tutorials!

Dime a Dozen
There really is a lot of support for XNA as far as tutorials, demos, and thousands of examples, perhaps tens of thousands of examples.

Here's just a couple I came across that I will be skimming to see how things are done.
Reimer's XNA Tutorial -can't really stand the ads though

And you can find a lot of good examples from XNA's site

That is all, just thought I'd share those. If anyone has any links to some good XNA resources, perhaps a game engine in XNA that would be cool to see.

Friday, December 12, 2008

3D Model Importers/Exporters Vanish!

Super Sleuth
So, an artist friend of mine and I were fixing to make a small single room game. Low poly models, basic collision detection, small number of effects. Just keeping it simple. I planned and started using jME. We wanted just very basic animation. So we needed to settle on a file format. I said COLLADA, since he was working 3dsmax9. So he eventually conceded to trying to get the plugin, after finding out that .obj is only for geometry. So he download the installer and what a surprise it didn't find his 3dsmax version.

Moving On
So we tried to find a MD5 importer/exporter but the plugin for Max didn't work. So on and on we went trying to get at least something to export from Max and load into jME. And nada niltch couldn't find a single decent plugin. I know from using a few plugins a while back with previous versions of Max it was a pain in the arse. And when exporting there was always a 50/50 chance something in the scene would cause the exporter to break. I recently started working with blender very nice free modeler and game oriented as well. I found that their support for exporting seemed to be pretty good. Although I now know that the updating of those export scripts is very sketchy at best.

Switching Gears
So I decided we'll switch to using XNA Game Studios which has a lot of support and makes DirectX childs play. No the matter became finding an appropriate .x exporter for Max well. While searching for 3dsmax plugin support I found very little at all and couldn't get a hold of the Panda Exporter it seems the site has completely vaporized, and most if not all the forums I checked mentioned that one.

Some Light Shines Through
So my friend was able to find a plugin with a funny little name, kwxport seems to be good from the first glance over. Kind of messed up the wind order and with backfacing turned on in the DirectX Viewer but that shouldn't be a problem since I can control which order it used. But I'm sure that this issue can be fixed.

Here's the nice low-poly hollow man:

It would be nice to know if there are some good exporters out there still for max. That and I've always been curious as to exactly which file formats work the best in commercial or even just quality indie games. So if you know of any please enlighten me?

Wednesday, December 10, 2008

Tower Of Defense to the Max Yo! (Defense Grid)

While aimlessly browsing youTube the the other night, for XNA games demos. I stumbled across a magnificently designed, and exceptionally beautiful looking Tower Of Defense game in development. I hail the designer for choosing to incorporate a semi-smarter AI than the run of the mill TOD especially on top of the amazing looking textures and detailed maps.

In my opinion this will mark a large development for the popular genre of casual strategy games, known as Tower of Defense. Especially since it is available for download from Steam and Direct2Drive. So for Steam I think this will be a good addition to the small list of notable games using the service.

Defense Grid - is a must for any TOD gamer, and definitely a tempting purchase for other gamers casual and hardcore alike!

Wednesday, December 3, 2008

My Game Making Future?

What does the future have in store for you?
I never thought I would actually be interested in reading blogs. Even when I first heard the term blog, and thought to myself, "is this person deficient, do they know how to speak english?". And later finding out that blog was short for web log. "How corny" was what came to my mind. And yes it still is, every damn time I say "I'm writing a blog post".

The Revalation
I believe that things happen for a reason and in the right sequence but we still have to grab a hold of the opportunities that are shoved in our faces. It's recognizing what is an opportunity and whether it can't hurt to grab on to it and hold on tight. See, recently I've been reading a Game Design Theory and Practice, Second Edition by Richard Rouse III. Starting a couple days before thanksgiving, and before I spent the weekend at my friends house just playing video games. I inevitably started thinking that I don't really make games I expirement with programming concepts. Ever pushing myself to understand all space partitioning algorithms or to write that next gen physics engine.

Self Denial
I realize that my belief that I have to create the next best technology in game engines, that perfect AI, or infinite content generation, is a total bust. I don't have to make the best engine or best OO design for my game. Trying to make it the most extendable or reusable. See there is a sin in OO programming that so many fall into. Or at least that I have fallen into, see I find myself anticipating abstraction for even the smallest number of repeated code. I try abstracting when I have as little as two pieces of code which have the same sequence of operations. It's not always productive to bother abstracting it when you only use it in a couple places and won't use it more often as you add more code. Also, I find myself trying to build abstraction layers for things that won't realize those abstractions.

And so all of this had lead me to start thinking in terms of creating games rather than neat little pieces of code that could be used in a game. That and I don't want to keep creating an engine that won't be suitable for a game or a Game Creator that didn't start making games at its earliest version.

The Press
I found this article very enlightening and inspirational as well as hopefull. It made me realize that if I want to create the next gen graphics engine, or physics engine. It couldn't hurt to actually own a studio that makes less technically advanced games and build up to that AAA titled. And of course "bedroom coders" as he calls them is what the video gaming industry is built on and it's definitely better to be in that group than to be a code monkey for a corporate giant or a limited studio who is known only for ports and movie games.

Tuesday, December 2, 2008

Back to Work: In 3D

The Sad Part:
Vacation time is over and now its back to the normal work week. And of course it means getting up as early as possible to be able to have more hours in the evening to spend on side projects. But at least there is another vacation right around the corner Christmas. Of course for me that means running around the South Jersey area from Mall to Mall window shopping for that perfect gift for my family and girlfriend.

The Goodies:
So, I've been getting back into 3D programming a little bit over the past couple weeks. For Java there are some good choices for your 3D programming needs. There is LWJGL and then JOGL which is now supported by SUN. Both are open source. And of course I believe that the Java Monkey Engine is probably what you should start with if you are thinking of getting into 3D programming with Java.

On the flip side of the coin for those C/C++ gurus there is always SDL which integrates with OpenGL so that you have the simplicity of SDL with the power of OpenGL at your finger tips. The downfall of course is that OpenGL is not object oriented and does not provide common model file format of course theres always COLLADA packages you could check out. There is of course DirectX, but remember DirectX 10 is Vista only, you will have to use DirectX 9.0c if you want to do development on XP.

Of course if you are into new 3D technologies you can make the easy switch to XNA. With a very large support community and a lot of good libraries and articles to add physics, ai, and animations to your game quickly. And of course the really cool added bonus of being able to deploy your game and playtest it on your own Xbox.

Good Alternatives
If you want a good supporting community, lots of plugins, and of cross-platform, graphics API agnostic, there is always Ogre3D. You want to use Python, no problem you can create you game using pyOgre. Or even Ruby yes there is a ruby Ogre project. And of course yes you can use Ogre in Java now with Ogre4j. And of course there is a dot net wrapper MOGRE.

Take the wheel:
There are of course a ton of 3D engines, game engines, toy graphics apis, and anything else you could possible conjure into your mind. Check out DevMaster's 3D engine list.

And there is always Google. Enjoy!

Thursday, November 27, 2008

Game Creator Project

Project Background:
I've been developing a pure java 2D game engine for about 3 years now. The code has evolved a lot since I captured it from a game that I started making called TechWrecker. That game originally started out being just a silly little project and kind of evolved into that last snapshot. As you can tell it needed a lot of work both coding and game design wise.

That game helped me develop the Game State Machine. As well as the Resource Manager and Input Manager. I recently begin redesign the resource manager to allow for loading levels, and animations, as well as other types of custom assets.

And so I decided to make an editor for a Animation file format that I created after I was able to compress BufferedImages using Java's Deflate utilities.

Project Overview:
A friend of mine whose working on a 2D side-scrolling shooter in GameMaker convinced me to create a level editor and to plan on making an actual Game Creator. Probably because he was frustrated with certain features. So I have a good start. Here is a development screenshot:

Not much to look at right now, and I hope to add icons to the toolbars. Some of the short-term features that I hope to have are:
  • Animated Sprite Tiles
  • Multi-Layered Levels
  • Entity placements and property settings
  • Collision Volume Data (per frame for Animations)
  • Level File Format (binary or xml with compression)
  • Image Editing and Touch-up

Wednesday, November 26, 2008

The Thanksgiving Special!

Off Topic
Ok so I know that up to this point I have kept the posts mainly about game programming and general programming topics. But I feel it is necessary for a bit of personality to emerge. I have been struggling with ideas for new posts and haven't had the will to really bring myself to sit down for a couple hours and hammer out the next method of collision detection. That and I've been debating between posting a polygonal collision detection algorithm, and a fast distance checking algorithm.

Original Purpose
My original idea for this blog was to archive neat pieces of code that I think would be very useful for game programmers. At about the same time as I created this blog I wanted to create a website with Effects tutorials mainly because that was one thing in game development that I was unable to find a lot of on the net. Yes there are tons of tutorials for basically any technique, ie. Water, Terrain, shader effects, texture filtering algorithms, toon shading examples, etc. But unless you pickup a book or take a course on game programming and design, you'd never know the right terminology to use in your google searches. Or even get the depth you need to successfully implement those techniques. Still almost everyday I find out about some new technique or some cool tutorials. I hope to be sharing those in the future.

Moving Forward
So in the future I hope to post about many topics, some more personal info about projects I'm working on, events in my life etc... And am gonna try my best to increase the frequency of my posts and keep them as useful as possible.

Finally Thankgiving!
I work fulltime now, after graduating back in May, being lazy for a few months, and then getting a job. And driving 80 miles to and from work every day for about a month. Until I found an apartment. Then there is the loans and getting used to the fact that I'm over 50,000 dollars in debt and have a very small income after all those bills are paid. Not to mention the fact that my job has been quiet boring and definitely not ideal. Basically not a game developer job.

So, having a 4 day weekend getting to spend time with lots of family and my girlfriend is going to be a lot of fun. Also, a very large home grown turkey is going to be key. As well as waking up and watching the Macy Day parade; tradition!

I hope you all enjoy your thanksgiving! Drive safe be careful and eats lots of turkey!

Tuesday, November 18, 2008

Rendering Hints: Java Anti-aliasing

Description of Purpose:
One of the neat things that the java.awt.Graphics2D class provides is the ability to turn on anti-aliasing for drawing primitives. This makes drawing vector graphics for your game much more attractive and simple. I will demonstrate a few usages for utilitizing anti-aliasing in hard-coded primitive animations to provide various effects.

The basic idea of anti-aliasing is that you soften the edges when drawing lines, circles, arcs, ovals, or any other primitive. You can read more about it here.

The example code will build upon what DoubleBuffering example code.


Quick And Dirty:
Enabling anti-aliasing for your Graphics2D objects is very easy. Just one function call and you've enabled it. It couldn't be simpler.

Using the setRenderingHint function in the java.awt.Graphics2D class.

Now any primitive that you draw, i.e. polygons, rectangles, arcs, ovals, etc... Using that graphics instance will be anti-aliased.

Pretty simple right, there are also other rendering hints that can help increase the quality of your graphics. However, it's a good idea to use them sparingly since they do require more time to render.

The Example:
The example can pretty easily be extended to provide a means for testing different mouse over effects or just animated effects in general. If you come up with neat effects that you would like to share please feel free to post them.

Friday, October 10, 2008

Bounding Box Collision Detection

Collision Detection
Detecting collisions is a major component of making games. There are several other methods which will be covered in other posts. So lets start with the basic method of collision detection and work our way from there. The first method that most beginners will come across is bounding box collision detection.

A bounding box is an invisible rectangle that defines an area where moving (i.e. dynamic objects) cannot move into or are contained within.

To define a bounding box you would use the following:
x coordinate
y coordinate
width of box
height of box

The x and y coordinates can be the location of the object. Say for instance all your objects are 32x32 pixel sprites then your bounding box may be (x,y,32,32) where x,y is the location of the object. In some cases you want your objects x and y to be the center of the actual image and in that case the bounding box may be offset from the x and y location. Such as (x-16, y-16, 32, 32).

Collision Checking
So, once you have a bounding box defined for your game objects you now need to check collisions only when necessary of every object with every other object and discard objects you've already checked against. There are many methods of separating your world to determine objects that might possibly collide. Including binning, binary space partitioning, quad trees, etc... Used in both 2D and 3D games.

So you have two rectangles rect1 and rect2 and you want to know if these two rectangles intersect.

So you need to check every point of one rectangle to see if any points are inside the other rectangle.

The four points are:
x+width, y
x, y+height
x+width, y+height

Here is how we check to see if a point is within the rectangle.
boolean inside(int x, int y, Rectangle rect) {
return (x > rect.x && x < rect.x+rect.width) &&
(y > rect.y && y < rect.y+rect.height);
The method above will return true if the point (x,y) is inside the rectangle. We can allow for collisions with the edges of the rectangle by changing the '>' and '<' operators to be '>=' and '<=' in the above function respectively, thus our function name might need to be changed to 'hitCheck'.
boolean hitCheck(int x, int y, Rectangle rect) {
return (x >= rect.x && x <= rect.x+rect.width) &&
(y >= rect.y && y <= rect.y+rect.height);
Final Step
So now that we can detect whether a point is inside, or hitting a rectangle we can now do our collision check between two rectangles.
boolean collisionCheck(Rectangle rect1, Rectangle rect2) {
return hitCheck(rect1.x, rect1.y, rect2) ||
hitCheck(rect1.x+rect1.width, rect1.y, rect2) ||
hitCheck(rect1.x, rect1.y+rect1.height, rect2) ||
rect1.y+rect1.height, rect2);
We can use the inside function, although that would mean our objects may appear to overlap when doing collisions.

Handling Collisions
So now that you can detect a collision what should you do when a collision happens. Well in a lot of games you usually only have a single moving object (player/avatar) that the user is controlling. A lot of static objects (buildings, walls, obstacles, etc...) So you don't need to collide a non-moving object (static object) with another non-moving object (i.e. two walls). And the player may not be moving all the time so you don't need to check collisions if he hasn't moved from the last time you checked collisions.

Therefore, only check collisions with moving objects and only if those moving objects have moved since the last time you checked for collisions. So here are the steps:
  1. Loop for all moving objects
  2. Did they move since the last time I checked them
  3. If they have, check collisions
  4. If we have a collision with an obstacle then revert to my last known position
Step 4 is common when moving objects around a level that has walls. Basically the object is moving it self to a new position but before we redraw him at that new position we check to see if he collides with anything, if he does then move him back to his original position.

The other option is to check collisions at the position the moving object wants to move and only do the move if there are no collisions with static objects at that point.

Example Code in C using SDL:

This code was tested with Dev-Cpp and SDL on WindowsXP. Any bugs or fixes please feel free to comment.

Monday, August 18, 2008

Introduction to Silverlight

If you haven't already encountered it among the interactive and browser games websites of the web, Silverlight is the relatively new web application framework created by Microsoft to directly compete with Adobe Flash. Like the familiar Flash applications, Silverlight provides user-interactive graphics (2D and 3D), animation, media-playback, and other features on web pages via an easy to install browser plugin. Currently there is not a great number of websites with Silverlight content, mainly due to the fact that version 2.0 is still in beta (the final release is due in early fall) and offers huge improvements over version 1.0 (latest release in April this year), but links are given to some examples/games in a section below. Both versions of Silverlight are based on WPF (Windows Presentation Foundation) - the new user-interface framework for Windows, intended to replace the long-standing Windows Forms infrastructure on the desktop and also take its place on the web. The declarative/XML-based approach of WPF tends to be very suitable for web development. The availability of a substantial portion of the .NET Framework 3.5 in Silverlight 2 adds many powerful features including network communication. Silverlight is also likely to take a main role in media playback/streaming with its in-built support for the WMV, WMA and MP3 codecs and free streaming service.

Silverlight or Flash?

Official support for Silverlight on Mac OS and the recent development of Moonlight for Linux distributions (supported by Microsoft) could very well encourage Silverlight to be adopted on all main OSs, therefore being able to compete with Flash on more than just Windows. It is also stable across all main browsers.

There are no apparent significant disadvantages of Silverlight compared to Adobe Flash. Listed here are some of the potential advantages of developing with Silverlight:
  • Power of the .NET Framework - unlike ActionScript (the language used to develop in Flash), C# and VB.NET (as well as the dynamic languages such as IronPython and IronRuby) are popular fully-fledged languages in which many developers are already skilled. The additional learning required to develop with Silverlight rather than Flash is therefore hugely lower (even without any knowledge of WPF). Furthermore, much of the .NET Framework 3.5 and its associated technologies such as WPF and LINQ are available to fully utilise.
  • Visual Studio - it is widely regarded (at least among Windows users) that Visual Studio (the 2008 release) is the best IDE around, possibly on any OS. Although Visual Studio and the Adobe Flash software are both commercial, Visual Studio Professional edition (required for Silverlight development) is available for free to students via the DreamSpark scheme. Microsoft Expression Blend, a design application for WPF/Silverlight, is also available to students via the same scheme.
  • Graphics & Animation - XAML and the WPF animation model provide a much more straightforward system to use that Adobe, which relies on binary formats for specifying graphics/shapes and only a frame-based (as opposed to time-based) animation system.
  • Windows Live Silverlight Streaming - Microsoft is offering free hosting and streaming for videos to Silverlight applications with your Windows Live account. Maximum bandwidth usage will be unlimited once it is out of beta. See silverlight.live.com for more information.
  • Microsoft has a huge ability to mass-distribute Silverlight to all Windows user, thereby enabling it to dominate or certainly at least challenge the current predominance of Flash. Depending on the success of the Moonlight project, Silverlight could gain populartity on Linux even before Flash.
Getting Started with Development

Everything you need to get started with developing using Silverlight 1.0 or 2.0, including instructions for setting up the development environment and beginner to intermediate-level tutorials/videos, can be found here.

Links to Silverlight Examples/Games

Silverlight Showcase

Microsoft Popfly (create your own games/mashups)

Line Rider (game)

Zero Gravity (game)

Diver (game)

Other games (game)

Friday, July 18, 2008

gpSnippets: Breaking into Silverlight

News: New Survey

Tutorials and snippets for Silverlight game development are coming to Game Programming Snippets. Theres a survey to see if you are interested in learning some cool techniques and libraries for Silverlight.

Silverlight: Synopsis

Since silverlight is very new and not many people are familiar with it I'll explain shortly what it is. In short it is Microsofts answer to Flash's continued advancement. Here is microsofts pitch from their Silverlight page.
Microsoft Silverlight is a cross-browser, cross-platform, and cross-device plug-in for delivering the next generation of .NET based media experiences and rich interactive applications for the Web.

Upcoming Snippets

An introduction with many links to showcase and help you get started with Silverlight. Hopefully there will be a basic getting started silverlight tutorial posted here as well. Along with an already available physics package with links and code snippets to help you. Stay tuned.

Feedback: Please!!!

Please offer any comments on what types of tutorials or snippets you would like to see either for Silverlight, Java, or C/C++. I am tremendously interested in offering my knowledge and experience to help you make successful games.

Sunday, July 13, 2008

Resource Manager Snippet

Basics of Resource Management

Java unlike C/C++ does not allow you to deallocate your own allocated memory. Nor does it allow you to know the size of physical memory used by an object. In games we need to allocate more and more resources as the game gets progressively longer. We wouldn't want to load all 50 1024x768 level backgrounds if we are making a puzzle game with unique backgrounds. Or say 500 64x64 animated sprites for a platformer. The VM will simply exceed its heap size limit and you'll see this nasty little message "java.lang.OutOfMemoryError" you can increase the heap size using VM command line arguments.

java -Xms -Xmx

The defaults are:

java -Xms32 -Xmx128

Even so you don't want to be eating up a users resources especially if you are an applet game or a mobile game. So you need some way of deallocating memory and releasing unused resources.

The Simple Method

The simple method is to allocate (load) resources and deallocate (remove all references to) manually. In the State Machine example posted here there was a cleanup method called on States before a transition occurs which is a good place to remove unused resources or you can just remove quickly loading resources since their inexpensive to reload when needed.

Alternative Resource Handling

A better method would be to encapsulate a reference to the resource within another object making sure that that object is the only one with a reference to the actual resource. The downfall here is that the Resource container object acts as a Proxy pattern to the resource itself. The upside is that you can set the resource up for garbage collection by simple setting the actual resources field to null. Here is a quick example class.

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageResource {

 //The one and only reference to the Image
 private BufferedImage realObject = null;

 private File resourcePath = null;

 public ImageResource(String path)
   throws IOException {
  resourcePath = new File(path); 

 public boolean isLoaded() {
  return realObject == null;

 public void reload() throws IOException {
  realObject = ImageIO.read(resourcePath);

 public void release() {
  realObject = null;

 public void render(Graphics2D g) {
  g.drawImage(realObject, 0, 0, null);

 public int getWidth() {
  return realObject.getWidth();

 public int getHeight() {
  return realObject.getHeight();
Another option to providing Proxy methods is to use a Visitor pattern for performing operations on specific Resource classes. But that is a more detailed idea for another day perhaps.

Singleton Resource Manager

If you want something to work with here is an example Resource Manager that handles loading Images, AudioClips and manually allocating and dereferencing resources. It's based on using a HashMap as the resource container and setting itself up as a singleton instance.

Saturday, June 28, 2008

Loading Images From a Jar File

Something Cool To Do With Jar Files

It's pretty simple really, of course there are a few ways to do it. I have seen it done in the following way.
I have had a lot of problems with this type of loading and I prefer a more direct approach which many people don't either know about or care to recommend for one reason or another. Here is how I tend to load images:
private Image fetchImage( String path ) {
  try {
   URL imgUrl = 
    new URL("jar:"+getJarPath()+"!"+path);
   return (new ImageIcon(imgUrl)).getImage();
  } catch (MalformedURLException e) {
  return null;
The main thing to note here is simply the "jar:" prefix to the jar file path string and the "!" suffix which indicates that anything after it is a location within the jar file itself.

Note: To get to subdirectories the path string must be something like this "/data/images/myimage.png". Therefore the entire URL would look something like the following: "jar:file:/C:MyProject/LoadingFromAJar/myJar.jar!/data/images/myimage.png"

The only downfall to using this method is that it requires you to know the name of the jar file that the image is within. The plus side to this is that your images can be located in any number of subdirectories within the jar file you can package all the contents of your jar file into separate directories without worrying about where they are located or if the Class Loader can find them or not.

Standalone versus Applets

So now that you can load resources from within a Jar file at runtime how can we make it easier to get the location of the Jar file because we need a complete and valid URL which means no relative paths.

So there are two situations we must account for separately. One is a jar file run using the command line or auto-executed as a standalone local application. For this we simply use a File instance:
String myJarFilePath = (new File("")).toURI().toURL().toExternalForm() + "MyJarFile.jar";
This works perfectly fine if you are running the jar file locally but in an Applet you will get a Security exception since you are not allowed to instantiate File class instances. But the Applet class gives you a way to determine the path.
String myJarFilePath = getCodeBase() + "MyJarFile.jar";
The above will only work in an Applet if it is done within or after the Applets init() method is called.

Package this all up into a nice ResourceManager and viola working code that you will never have to touch again and can reuse in any project at anytime. I will post a simple ImageManager class example for your use very soon.

Thursday, June 26, 2008

Building Your Own Image Loader

Images Needed
When programming games images are one of the things that just comes pretty standard. Whether its textures for 3D models, 2D background images, or even sprite sheets. There are a variety of formats for image files here are just a few, jpg (jpeg), gif, tga, pcx, png, and bmp. Some of the formats are compressed jpg & gif for example but their compression comes at the cost of accuracy. If you save an image in paint in either of these formats then reopen it you will see that the pixels color changed slightly. The bmp format or bitmap is uncompressed thus taking up a lot of space. The best format for both accuracy and compression is png. So for pretty much any graphics in game programming they tend to be used more often then not. Another nicety is pngs support an alpha channel useful for not fully transparent images.

Common ways of Loading Images
The most common way that I've seen to load images in Java is by using ImageIcon. It was also the first that I learned. It's very simple.
//substitute myImagePath for the relative or absolute path and file name
Image img = (new ImageIcon(myImagePath)).getImage();
AWT Toolkit provides another way of loading images
//substitute myImagePath for the relative or absolute path and file name
java.awt.Toolkit awtkit = Toolkit.getDefaultToolkit();

//this method might cause memory issues
Image img = awtkit.getImage(myImagePath);
//recommended to use this instead.
img = awtkit.createImage(myImagePath);
These two methods are about all you really need to load images. But both of these methods do not load BufferedImages but rather only images. I believe they are VolitileImages.

There is a third alternative for image loading javax.imageio package contains a ImageIO class that can be used to load BufferedImages.
//Load a buffered image.
BufferedImage bImg = ImageIO.read(myImagePath);
This class is useful because it provides a means of loading a buffered image. The use for a buffered image is that it provides a way to extract parts of the image itself as separate images which is very useful for sprite sheets and tilesets.

The Loader
The basics of a loader is to hold on to images that are currently loaded. There are many advantages to using an image loader. You can detect when an OutOfMemoryError occurs and release existing images to free memory. You can load arrays of BufferedImages or whole directories even load all resources in a given directory and its subdirectories.

One of the extremely useful things about a loader is you can configure it to load images from inside a jar file. Which I will explain how to do later?

Monday, June 23, 2008

Car Smoke trails using Particle Effects

I've been working on a Particle Effects engine during the last week or so and the results turned out quiet nice so far. It took a lot of tweaking and using some hacked together physics for the car movement but overall I think it is good enough to show off a little.

I'll be cleaning up the Particle Engine code and making a post explaining how to go about creating your own particle effects engine as well as providing a sample engine for people to work from.

You'll need at least Java 5 plugin for your browser in order to view the applet. Click on the applet and use the right and left arrow keys to move the car respectively. The responsiveness of the car isn't very good but it demonstrates a use for the particle effect.

Friday, June 13, 2008

Particle Effects

So I decided to fiddle around with Particle Effects and came up with a simple demo drawing simple spheres to the screen. The idea of a good Particle Effects engine is to be efficient and to not bog down imperative rendering operations.

You don't want your sprite animation to suffer speed slow downs because of your particle effects. You would rather want the particle effects engine to scale to meet the load requirements of your game.

I created a simple particle emitter for prototyping purposes. I packaged it into an applet so that I can embed it in this post. Speeds will differ depending on your browsers performance and CPU, graphics card, etc...

Get the latest version of java to see this applet Sun Java

Right now its just a simple demo that I hope to expand and integrate into the 2D engine that I have been developing.

Wednesday, May 21, 2008

Cool Flash Game: Magic Pen

Magic Pen is I guess you could say a puzzle game. The interesting mechanic of the game is being able to draw object that are immediately effected by gravity once they are finished being drawn. Its a very fun game and you can make things and watch them go.

It would be nice if there was a larger space do create things in and you can just do whatever you wanted. Kind of like line rider were you have free rein and a lot of drawing space.

Here is a link: http://magic.pen.fizzlebot.com/magic-pen.swf

Thursday, April 3, 2008

Who likes platformers? Check out the Old School

One of the things that amazed me about this particular find was the pixelatted graphics and the retro feeling. Brought back some memories of a lot of old games. Definitely Something I will have to play all the way through no matter how long it takes.

The Site: konjak.org

The Game: Noitu Love

I will probably post some more details about other games and see if I can't get an inside scoop on the developer.

Monday, March 24, 2008

Keyboard Input: Polling System In Java

When I first started game programming and well into about 4 years of it. I always wondered the reason for wanting to use a polling system for Input instead of an interrupt based method. Now I know why and I'll share with you.

I figured it was better to receive an interrupt event than constantly checking the state of every key on the keyboard. But in games its imperative to have our objects updating on a fixed framerate structure and order is primary. Thus if we were to use an interrupt based system it would destabilize when events occur. Sure it is possible to use Java's KeyListener interface for all our keyboard handling needs. But there is a bit more overhead than simply making a single listener that stores the state of each key on the keyboard for us to poll.

The main problem with KeyListener is it tempts us to write all our event handling code in the keyPressed, keyReleased, keyTyped methods which for games is very bad. Since it might take XX amount of milliseconds to execute our event handling code handling multiple events per frame won't do, usually you don't wanna be taking that much time handling your input anyways. The more important reason is that every KeyListener will run in a separate thread while handling the input which means you will have to handle any synchronization issues that might come up while developing.

Those are just a few reasons why you might want to use a keyboard polling system in a Java game.

Basic Start
So lets start with the basics of the idea. For our purposes we'll make it a singleton but if you have an existing design and can integrate it without using a singleton I would recommend it.
class InputManager implements KeyListener

     private static InputManager singleton = null;

     protected InputManager() {

     public static InputManager getInstance() {
          if(singleton==null) {
               singleton = new InputManager();
          return singleton;
So now we need to add an array to save the keyboard state. I use two arrays of 256 boolean values. One array is for holding a single true false, down or not or up or not state.
private boolean[] key_state_up = new boolean[256];
private boolean[] key_state_down = new boolean[256];
You could just store a single integer or short array using different values for the keys state which would allow you more states but since there really aren't any other states boolean arrays will do just fine. So here you can see we have a single variable we can set for each of the 256 keys on the keyboard. This allows us to track multiple keys being pressed simultaneously, needed for fighting games and the like something we would have to do with boolean variables in each KeyListener implementor if we weren't using a single InputManager.

This allows the key state to remain fairly consistent during a single frame in the game update cycle and reset at the end of the cycle. So as long as our update is not taking forever and runs quickly the response time is pretty quick.

What more could you want?
So thats nice but what else, well we sometimes want to just check to see if the user pressed something. We don't necessarily care what it was just if they pressed something. So we add another couple bools for that.
private boolean keyPressed = false;
private boolean keyReleased = false;
So this allows us to make those nifty little pause screens or making sure we don't eat up the users CPU without making sure their using the game first. Usually you have something like "Press any key to continue" or whatever.

Getting Input
Now we need to actually make our InputManager instantiable by adding the KeyListener interface method implementations.
 public void keyPressed(KeyEvent e) {
  //System.out.println("InputManager: A key has been pressed code=" + e.getKeyCode());
  if( e.getKeyCode() >= 0 && e.getKeyCode() < 256 ) {
   keys[e.getKeyCode()] = (int) System.currentTimeMillis();
   key_state_down[e.getKeyCode()] = true;
   key_state_up[e.getKeyCode()] = false;
   keyPressed = true;
   keyReleased = false;

 public void keyReleased(KeyEvent e) {
  //System.out.println("InputManager: A key has been released code=" + e.getKeyCode());
  if( e.getKeyCode() >= 0 && e.getKeyCode() < 256 ) {
   keys[e.getKeyCode()] = 0;
   key_state_up[e.getKeyCode()] = true;
   key_state_down[e.getKeyCode()] = false;
   keyPressed = false;
   keyReleased = true;

 public void keyTyped(KeyEvent e) { 
  keyCache += e.getKeyChar();
Here we use the key code as the index for setting each of the key state.

To use the InputManager you will need to add it as a KeyListener, MouseListener, MouseMotionListener to either your JPanels or JFrames that you are using. Also, at the end of every update frame you will want to call the InputManager.update method to reset the key_up_states.

Here is the full InputManager class I use in my Java 2D engine.
  • InputManager.java - it's back again, let me know if there are issues with this class.
  • InputManagerTest.java - This is a basic test class which shows how to utilize the InputManager to handle basic keyboard events in a polling loop as well as showing how many events you could receive based on your polling rate.