I am creating a basic game of space invaders. I am using a thread to animate the game and was wondering, how do I get the aliens the speed up going left and right without changing the speed of the ship you control below them?
What is the easiest method? I am quite new to Java 2d and have only created two other more basic games.
First of all instead of using a thread i advise to look at active rendering.
Active Rendering article
Oracle (Sun) resource on the topic
Active rendering (Figure 2) is just the opposite. Instead of letting
someone else decide when to paint, the program constantly repaints the
screen in a very tight while loop. While this sort of behavior is not
recommended for regular applications, it is exactly the kind of
control needed to make computer games.
The main difference compared to regular rendering is that you don’t wait for the paintXYZ() to be called but you intentionally redraw the screen as fast as you can (FPS) to have a smooth game experience.
Then you set up different horizontal and vertical speeed for your characters. And whenever a new ‘frame’ kicks in your game objects will be moved with the designed pixel distance.
I give you some resources that will be fruitful to you:
- Space Invaders – A Java 2D Tutorial
- Java 2D Games Tutorial
- Some Java 2D/3D Tutorials
- 2d simplistic space invaders game in Java
- Space Invaders – 2D Rendering in Java
- Creating a Java platform game as easily as possible
Your frame rate shouldn’t be tied to the content of the frame, and the trajectory of each object over time should be independent. When preparing a frame representing time “x”, each moving object has it’s own position.
The basic idea when doing this is to give each object a Speed
property, and then have a timer variable.
For each frame, when rendering:
- Calculate the length of time since you started rendering the last frame, in milliseconds. Call this
Delta
. - Update the timer with the current timestamp.
- For each object, use
Delta
and the object’sSpeed
property to determine its new position. - Render all objects at the correct position.
Note that in this model movement speed is tied to time elapsed, and not to the rendering itself. This way, if your frame rate goes up or down for whatever reason, things still move at a consistent rate.