Im making a basic space invaders game. I got all the resources from the LWJGL .zip file (Im not using LWJGL librarys to create my game, just got the pictures, etc. from it.) Any
You will need to store the location of the "bullet" somewhere, and then access that state within your paintComponent(Graphics g)
method. Really, this should be factored out quite a bit. Make your Shot
class look something like this:
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
}
}
Then in your key pressed method,
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();
}
And you'll extend JPanel
and override 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
}
}
That's the basic idea. Hope it makes some sense now. You could move the Shot
's drawing code elsewhere, I suppose, but for simplicity, I just stuck on the Shot
class itself.
I will note that what I have above is some pretty messy code. Look into the MVC pattern. It makes for much cleaner state abstraction (decouples the state from the display code).
The idea is that the listeners should change the state of the game (i.e. create a bullet, or change the location of the bullet, or whatever), and then call repaint()
. Then Swing will invoke the paintComponent(Graphics g)
method, which will paint the updated game state using the Graphics passed as argument.