我目前正在开发一个Java战斗游戏,但我遇到了障碍。
基本上,我有两个线程在运行:一个线程由画布实现,它更新绘制到屏幕上的所有内容,然后睡觉;另一个线程由字符类实现,它只更新字符的位置。我在画布类中还有一个子类,它实现KeyListener,并为键的状态更改一个布尔变量,如果按了up按钮,那么字符自己的up布尔变量也会被更新。
我的问题是,当我按下键盘上的一个按钮时,输入肯定是在画布一侧进行的(我已经用打印语句确认了输入),但它并不总是指向字符,我只能假设,由于字符的位置更新在一个单独的线程中运行,所以出现了一个问题。
这是我的相关代码:
//
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
}
}所以很明显,我是Java游戏编程的初学者,我可能没有最好的编码实践,所以你能提供的任何其他建议都是很棒的。然而,我脑海中的主要问题是,由于某种原因,我的角色有时只是拒绝接受键盘输入。有人能帮忙吗?
发布于 2015-03-26 16:01:42
您可能需要使成员upPressed不稳定,以便在线程之间正确地共享它。尝试在upPressed的定义中添加易失性关键字。
例如:
public volatile upPressed = false;使用易失性变量降低了内存一致性错误的风险,因为对易失性变量的任何写入都会在与该变量随后读取的关系之前发生。这意味着对易失性变量的更改对其他线程总是可见的。
https://stackoverflow.com/questions/29283221
复制相似问题