So I'm programming a game using Swing and AWT and I'm getting a weird error. As I check for input in my MenuState, which is just my Menu screen, it is telling me that the timeout value in my game loop.
MenuState.java:
package GameState;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import Handlers.MyInput;
import TileMap.Background;
public class MenuState extends GameState {
private Background bg;
private int currentOption = 0;
private String [] options = {
"Start",
"Help",
"Quit"
};
private Color titleColor;
private Font titleFont;
private Font font;
MenuState(GameStateManager gsm) {
super(gsm);
try {
bg = new Background("/Backgrounds/Menu.gif", 1);
bg.setVector(-0.1, 0);
titleColor = new Color(128, 0, 0);
titleFont = new Font("Jokerman", Font.PLAIN, 22);
font = new Font("Times New Roman", Font.PLAIN, 12);
} catch(Exception e) {
e.printStackTrace();
}
}
public void update() {
bg.update();
handleInput();
}
public void draw(Graphics2D g) {
bg.draw(g);
//draw title
g.setColor(titleColor);
g.setFont(titleFont);
g.drawString("Suddenly, Cold Pizza", 55, 70);
g.setFont(font);
for(int i = 0; i < options.length; i++) {
if(i == currentOption) {
g.setColor(Color.BLACK);
} else {
g.setColor(Color.RED);
}
g.drawString(options[i], 145, 140 + i * 15);
}
}
public void init() {
}
private void select() {
switch (currentOption) {
case 0:
//start
break;
case 1:
//help
break;
case 2:
//close
System.exit(0);
}
}
public void handleInput() {
if(MyInput.isPressed(MyInput.BUTTON6)) {
select();
} else if(MyInput.isPressed(MyInput.BUTTON2)) {
if(currentOption > 0) {
currentOption--;
}
} else if(MyInput.isPressed(MyInput.BUTTON4)) {
if(currentOption < options.length - 1) {
currentOption++;
}
}
}
}
And then the function that contains my game loop:
GamePanel.java:
public void run() {
init();
long start;
long elapsed;
long wait;
boolean first = true;
//game loop
while(isRunning) {
//start time
start = System.nanoTime();
update();
draw();
drawToScreen();
//time elapsed
elapsed = System.nanoTime() - start;
//frame wait
wait = targetTime - elapsed / 1000000;
if(wait < 0) {
wait = wait + 20;
}
try {
Thread.sleep(wait);
} catch(Exception e) {
e.printStackTrace();
}
}
}
I'm getting the error in the Thread.sleep(wait). It says I have a negative value for wait, but in debugging, the value never appears to be negative.
If you need any more information, let me know and I'll post it.
java.lang.IllegalArgumentException: timeout value is negative at java.lang.Thread.sleep(Native Method) at Main.GamePanel.run(GamePanel.java:95) at java.lang.Thread.run(Thread.java:745)
\$\endgroup\$targetTime
is set to1/FPS
, whereFPS = 60
. \$\endgroup\$