1

我正在制作上述模式的 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

4

1 回答 1

8

哎呀!

new Thread(new Shoot()).run(); // ***** !!!!

您不会通过调用线程的run()方法来启动线程,因为所做的只是调用与调用代码相同的线程中的代码。你通过调用它的方法来启动一个新的线程。start()

于 2013-02-19T03:37:42.803 回答