gpt4 book ai didi

java - 在 Java 游戏中的两个线程之间同步键盘输入

转载 作者:行者123 更新时间:2023-12-01 11:44:14 25 4
gpt4 key购买 nike

我目前正在开发一款 Java 格斗游戏,但遇到了障碍。

基本上我有两个线程在运行:一个由 Canvas 实现,更新绘制到屏幕上的所有内容,然后 hibernate ;另一个由 Canvas 实现。一种由角色类实现,仅更新角色的位置。我在 Canvas 类中还有一个子类,它实现 KeyListener 并为任何键的状态更改更改 boolean 变量,并且如果按下向上按钮,则角色自己的向上 boolean 变量也会更新。

我的问题是,当我按下键盘上的按钮时,输入肯定会在 Canvas 端进行(我已使用 print 语句确认),但它并不总是会传递到角色,这是我可以解决的问题仅假设是由于角色的位置更新在单独的线程中运行这一事实而引起的。

这是我的相关代码:

//
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 游戏编程的初学者,我可能没有最好的编码实践,所以您能提供的任何其他建议都会很棒。然而,我脑海中的主要问题是,由于某种原因,我的角色有时只是拒绝接受键盘输入。有人可以帮忙吗?

最佳答案

您可能需要使成员 upPressed 可变,以便在线程之间正确共享。尝试将 volatile 关键字添加到 upPressed 的定义中。

例如

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.

关于java - 在 Java 游戏中的两个线程之间同步键盘输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29283221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com