1

我正在制作一个基本的太空入侵者游戏。我从 LWJGL .zip 文件中获得了所有资源(我没有使用 LWJGL 库来创建我的游戏,只是从中获得了图片等。)无论如何,每当我在键盘上按“空格”时,我的 KeyListener 都会创建一个新的我的船发射的子弹。但是,我不知道如何绘制子弹图像,因为我的 KeyListener 没有传递图形对象,而您需要一个来绘制图像。导致问题的代码是“Shot”构造函数中的“drawImage”方法。这是我的代码:

    public class KeyTyped{

    public void keyESC(){
        Screen.isRunning = false;
    }

    public void keyLEFT() {
        Screen.shipPosX -= 10;

    }

    public void keyRIGHT() {
        Screen.shipPosX += 10;

    }
    //This is automatically called from my KeyListener whenever i 
    //press the spacebar
    public void keySPACE(){
        if(!spacePressed){
            ShotHandler.scheduleNewShot();
        }else{
            return;
        }
    }


}

公共类 ShotHandler {

public static int shotX = Screen.shipPosX;
public static int shotY = Screen.shipPosY + 25;




public static void scheduleNewShot() {
    //All this does is set a boolean to 'false', not allowing you to fire any more shots until a second has passed.
    new ShotScheduler(1);


    new Shot(25);
}

}

公共类 Shot 扩展 ShotHandler{

public Shot(int par1){

    //This is my own method to draw a image. The first parameter is the graphics object that i need to draw.
    GUI.drawImage(*????????*, "res/spaceinvaders/shot.gif", ShotHandler.shotX, ShotHandler.shotY);

}
            //Dont worry about this, i was just testing something
    for(int i = 0; i <= par1; i++){
        ShotHandler.shotY++;
    }
}

}

多谢你们!任何帮助将不胜感激!

4

2 回答 2

5

这个想法是听众应该改变游戏的状态(即创建一个子弹,或改变子弹的位置,或其他),然后调用repaint(). 然后 Swing 将调用该paintComponent(Graphics g)方法,该方法将使用作为参数传递的 Graphics 绘制更新的游戏状态。

于 2013-07-26T22:47:00.650 回答
1

您需要将“子弹”的位置存储在某处,然后在您的paintComponent(Graphics g)方法中访问该状态。真的,这应该考虑很多。让你的Shot班级看起来像这样:

public class Shot {
    private Point location; // Could be Point2D or whatever class you need

    public Shot(Point initLocation) {
        this.location = initLocation;
    }

    // Add getter and setter for location

    public void draw(Graphics g) {
        // put your drawing code here, based on location
    }
 }

然后在你的按键方法中,

public void keySPACE(){
    // Add a new shot to a list or variable somewhere
    // WARNING: You're getting into multithreading territory.
    // You may want to use a synchronized list.
    yourJPanelVar.repaint();
}

您将扩展JPanel和覆盖paintComponent.

public class GameScreen extends JPanel {
    public paintComponent(Graphics g) {
        for (shot : yourListOfShots) {
             shot.draw(g);
        }
        // And draw your ship and whatever else you need
    }
 }

这是基本的想法。希望现在有点意义。我想你可以将Shot's 的绘图代码移到别处,但为了简单起见,我只是停留在Shot类本身上。

我会注意到我上面有一些非常混乱的代码。查看 MVC 模式。它使状态抽象更加清晰(将状态与显示代码分离)。

于 2013-07-27T00:09:25.967 回答