Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question

4 Answers 4

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.

share|improve this answer

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.

share|improve this answer

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's Speed 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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.