I am trying to make a very simple space shooter game. I am using GAGE timer.
I want to run the game at full speed (max fps possible). The starfield
runs fine if I remove the line
SystemTimer.sleep((lastLoopTime + 10) - SystemTimer.getTime());
But then the spaceship does not move well (well, even with the line above
the movement of the spaceship is crappy). What should I do to have
a smooth starfield and my player(the spaceship) movement?
Thanks for the help, below is part of my code.
Here is the game loop on the main class:
private void gameLoop() {
long lastLoopTime = SystemTimer.getTime();
while (this.running) {
long delta = SystemTimer.getTime() - lastLoopTime;
lastLoopTime = SystemTimer.getTime();
lastFpsTime += delta;
fps++;
if (lastFpsTime >= 1000) {
frame.setTitle(" (FPS: " + fps + ")");
lastFpsTime = 0;
fps = 0;
}
Graphics2D g = (Graphics2D) this.strategy.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, 800, 600);
g.setColor(Color.white);
stars.render(g);
stars.move();
if (!this.waitingForKeyPress) {
for (int i = 0; i < this.sprites.size(); i++) {
Sprite sprite = (Sprite) sprites.get(i);
sprite.move(delta);
sprite.draw(g);
}
}
g.dispose();
this.strategy.show();
this.player.setDx(0);
if ((this.leftPressed) && (!this.rightPressed)) {
this.player.setDx(-100);
} else if ((this.rightPressed) && (!this.leftPressed)) {
this.player.setDx(100);
}
SystemTimer.sleep((lastLoopTime + 10) - SystemTimer.getTime());
}
}
Here is the code of the move method on the Sprite class:
public void move(long pDelta) {
this.x += ((pDelta * dx) / 1000);
this.y += ((pDelta * dy) / 1000);
}
Here is the starfield code:
public class StarField
{
private static final int STAR_MAX = 50;
private int screenWidth;
private int screenHeight;
private int x[];
private int y[];
private int speed[];
public StarField(int pScreenWidth, int pScreenHeight)
{
this.screenWidth = pScreenWidth;
this.screenHeight = pScreenHeight;
this.x = new int[STAR_MAX];
this.y = new int[STAR_MAX];
this.speed = new int[STAR_MAX];
for(int i=0; i < STAR_MAX; i++) {
this.x[i] = (int)(this.screenWidth * Math.random());
this.y[i] = (int)(this.screenHeight * Math.random());
this.speed[i] = (int)(3 * Math.random()) + 1;
}
}
public void render(Graphics2D g)
{
for(int i=0; i < STAR_MAX; i++) {
g.drawLine(this.x[i], this.y[i], this.x[i], this.y[i]);
}
}
public void move()
{
for(int i=0; i < STAR_MAX; i++) {
this.y[i] += this.speed[i];
if(this.y[i] > this.screenHeight)
this.y[i] -= this.screenHeight;
}
}
}