我正在制作一个基本的太空侵略者游戏。我从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++;
}
}
}
谢谢你们!任何帮助将不胜感激!
最佳答案
您将需要将“项目符号”的位置存储在某个位置,然后在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
的绘图代码移动到其他地方,但是为了简单起见,我只是停留在Shot
类本身上。我将注意到上面我有一些非常凌乱的代码。查看MVC模式。它使状态抽象更加清晰(将状态与显示代码分离)。