Java Game Tutorial - Part 3
This tutorial is a small add on to part 2 of my Java Game Tutorial. I have had many requests by people for this so I finally decided to put this part 3 of my Java Game Tutorial together.
In this tutorial you will see how to change from using those boring shapes to using images.
The first thing you will need is two 20x20 pixel gif or jpeg image. If you are using gif you must make sure you save it as 8bit Paletted. I have sometimes had problems if this is not done.
One image will be the alien type characters. I have smiley faces in my game.
Also you will need some sort of ship which does the shooting down the bottom.
These can be animated gif images if you would like to add some extra effect to them.
Now to the coding
This is very simple and will not take very long at all.
In the global variable section place the following:
This will set up two image objects to store out images.
Next is in the “public void init()” function. Place in the following code.
alien = getImage(getDocumentBase(), "img1.gif");
ship = getImage(getDocumentBase(), "img2.gif");
This will load the image files into the Image objects.
The final part is to then draw the images to our buffer.
The first one to draw are the aliens
We are currently drawing them with this line:
bufferdImgSurface.fillOval(currentX[i], currentY[i], 20,20);
Replace that line with this line
bufferdImgSurface.drawImage(alien, currentX[i], currentY[i], this);
This draws the image ‘alien’ to the current position in the buffer.
The same goes for the ship.
Replace this line:
bufferdImgSurface.fillRect(shipX, shipY, 20, 20);
With this line:
bufferdImgSurface.drawImage(ship, shipX, shipY, this);
You should now be able to compile this code and run it. If you have any errors such as getting a white or grey java frame then check your paths for your images. Make sure they are in the same directory with your class file. You can put paths in if you want by doing the following.
alien = getImage(getDocumentBase(), "folder1/folder2/img1.gif");
That is the end of my third tutorial for making games in Java.
I hope you like my tutorial. If you find any errors please email me, also if you have any comments please email me.
Also if you have something you think I could put in a future tutorial like multi player or networking email me.
If you would like to see a working version go here http://www.jcroucher.com/javatutg3.html
*Note: This tutorial has been compiled and tested with J2sdk 1.4.0_01 attempting to run or use this tutorial without this version JSDK or JRE can have bad effects. Use these at your own risk*
Also check out my website for more tutorials and code samples www.jcroucher.com
This code and tutorial is copyright 2003 John Croucher.