我正在制作上述模式的 2D Zombie Shooter,但我遇到了一些线程问题。这是交易。每次按空格键时,我都会让角色射出一颗子弹。问题是,如果你保持空间,它会发射一个,然后暂停,然后发射很多子弹。有很多方法可以解决这个问题,但我想要这种方式,因为它为未来改变拍摄速度留下了空间。这是导致问题的线程的代码:
package threads;
import Game.GameCore;
public class Shoot extends GameCore implements Runnable {
/**
* WHEN I START THIS THREAD, THE ENTIRE GAME FREEZES, AND I DO NOT KNOW
* WHY... NEED TO FIX. IT DOES NOT FIX THE PROBLEM TO TAKE OUT THE "SHOOT"
* OR THE "SLEEP"...
*/
public void run() {
while (shooting && gameRunning) { // shooting is made true when space is
// pressed, and set false when space
// is released. gameRunning is true
// if the game is running, which it
// is. removing either of these
// doesnt work either.
player.shoot(); // player comes from the GameCore class, and
// represents the player entity. if i remove this,
// nothing changes.
try {
Thread.sleep(bulletShootSpeedMillis); // bulletShootSpeedMillis
// is equal to 1000, but
// makes no difference
// to change
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
所以这是该死的问题。评论有点指出它们,但我列出了它们。如果我删除明显的东西,例如,player.shoot();
甚至Thread.sleep(bulletShootSpeedMillis);
是 while 循环中的东西之一,没有任何变化。问题是当我初始化线程时,
else if (key == Integer.parseInt(commands[6])) {
shooting = true;
new Thread(new Shoot()).run();
}
整个游戏只是冻结。什么都没有发生。当我用空格开始线程的那一刻,我的游戏冻结了,我不知道为什么!!!以前的版本:
else if (key == Integer.parseInt(commands[6])) {
player.shoot();
}
它工作得很好。请帮忙!提前致谢!:)
编辑:感谢您的快速回答。不用说,主要的学习经验,简单的错误XD