Reputation: 1
I'm currently developing a Java fighting game, but I've hit a road block.
Basically I have two threads running: one implemented by a Canvas that updates all things drawn to the screen and then sleeps; and one implemented by the character class that simply updates the character's position. I also have a subclass in the Canvas class that implements KeyListener and changes a boolean variable for whatever key's state was changed, and if, say, the up button was pressed then the character's own boolean variable for up is updated as well.
My problem is that when I press a button on my keyboard the input is definitely going through on the Canvas side (I have confirmed it with print statements), but it does not always go through to the character, a problem I can only assume is arising due to the fact that the character's position update is running in a separate thread.
This is my pertinent code:
//
public class GameWindow extends Canvas implements Runnable {
...
private KeyInputManager input; //Just implements KeyListener
private Thread animator;
private Character player1; //My character class
...
public GameWindow() {
...
input = new KeyInputManager();
player1 = new Character();
animator = new Thread(this);
animator.start();
...
}
...
public void run() { //This is in the Canvas class
while (true) {
if (input.isKeyDown(KeyEvent.VK_UP) {
character.upPressed = true;
}
...
player1.updateImage(); //Update the character's graphics
gameRender(); //Draw everything
try {
Thread.sleep(10);
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
...
}
public class Character implements Runnable {
...
Thread myThread;
...
public Character() {
...
myThread = new Thread(this);
myThread.start();
...
}
...
public void run() {
if (upPressed) {
//This is where all my jumping code goes
//Unfortunately I barely ever get here
}
...
//The rest of my position update code
}
}
So clearly I'm quite a beginner with game programming in Java and I may not have the best coding practices, so any other advice you can offer would be great. However, my the main issue on my mind is the fact that, for some reason, my character simply refuses to accept keyboard input sometimes. Can anyone help?
Upvotes: 0
Views: 991
Reputation: 13570
You probably need to make the member upPressed volatile such that it is correctly shared among threads. Try adding the volatile keyword to the definition of upPressed.
e.g.
public volatile upPressed = false;
Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads.
Upvotes: 1