I have recently been interested in Java Swing and Game development, so naturally I began creating many different 2D games.
During them I found myself having to rewrite much code, but eventually I decided to write some classes that would help me whenever I wanted to make a game.
Here is the basics for a single threaded game loop with multiple user input (i.e player moves with W, S, A and D and player 2 with UP, LEFT, RIGHT, and DOWN. Player1 can shoot with SPACE and player 2 wuth ENTER)
Basically there is an abstract class GameLoop
which require you too override draw()
, update(float elapsedTime)
and checkCollisions()
. This GameLoop will that be started and will call those methods as to render the screen at a set amount of frames per second. It uses a Fixed Time Step Game loop and is startable, pauseable/resumable and stopable. See here for more.
Next we have an Animator
class which basicaly allows us to add an ArrayList
of BufferedImage
s and timings for the images to be displayed. This class is mainly there to be used with GameObject
. If you were wondering wwhy GameLoop had a method update(float elapsedTime)
it is for the Animator
class so it know how much time has passed and wether or not it should change images currently displayed.
GameObject
class as the name suggest represents any object that we can draw to the GamePanel
. It extedns the Animator
class which allows it the functionality to have multiple images/sprites added to the Gamebject and displayed. It featires some advanced things like the direction the sprite is currently facing (i.e a person face from side view has to go left or right and image must be visually facing forward in that direction in this case it has to do with which side the bullets go depeding on which direction GameObject
is going)
Bullet
simply an extension of GameObject
and is used so I could have a more meaningful game :)
Next is ImageScaler
this was added for some over the top functionality IMO. It allows us to define a screen size that is standrad for our sprites i.e sprite is 100x100 when GUI is 800x600. Now usually if we changed the screens size for our app we would have to go an change all the picture etc, this method makes it easir for us to scale the images to new sizes in resepect of the current given frame/gui size.
KeyBinding
is a class which is just a wrapper for the methods needed to add KeyBindings to Swing components.
GamePanel
is the class which extends JPanel
and in which all of the above come together, It holds an ArrayList
with method to allow addition of GameObject
s etc, tese are than drawn in paintComponent(..)
it does have some extras too like anti-aliasing etc. Here is where we see some simple collsions detection taking place checking wether the Rectangle2D
of the GameObject
s intersects etc createAndShowGui()
method also holds some important code which sets up everything including GamePanel
.
I hope this will help others out there when creating their own games (even if if just the ideas)