I realize that a major component missing from my game is a sense of time, ticks, or FPS. I am planning on implementing this soon, but wanted to get some feedback on how to set up my "bullets" instead. I want the user to press the space bar and have a bullet fired across the screen. Now I have gotten close without a sense of FPS; however, it just draws as one giant line, meaning the bullet "trail" never clears. I am wondering why, when I call repaint, the rectangle can move around the screen via my keyboard, but whenever I have something set automatically to move then it just leaves a "trail", even though I am calling repaint();
in each method.
Also, how could i create my bullet from another class?
public class drawingComponent extends JComponent implements KeyListener {
public Rectangle hello = new Rectangle(300, 100, 50, 50);
Rectangle bullet = new Rectangle(310,75, 10,10);
boolean goingon = false;
public drawingComponent(){
addKeyListener(this);
}
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
g2.setColor(new Color(255,25,0));
g2.setFont(new Font("monospace", Font.BOLD+Font.ITALIC, 30));
g2.drawString("nothing yet",300,320);
g2.fill(hello);
setFocusable(true);
requestFocus();
g2.setColor(new Color(0,25,0));
if (goingon == true){
while (bullet.y < 1000){
bullet.y=bullet.y+10;
g2.fill(bullet);
}
bullet.y=300;
}
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_W){
hello.y=hello.y-1;
hello.setLocation(hello.x,hello.y);
repaint();
System.out.println(hello.y);
}
if(e.getKeyCode() == KeyEvent.VK_S){
hello.y=hello.y+1;
hello.setLocation(hello.x,hello.y);
repaint();
}
if(e.getKeyCode() == KeyEvent.VK_A){
hello.x=hello.x-1;
hello.setLocation(hello.x,hello.y);
repaint();
}
if(e.getKeyCode() == KeyEvent.VK_D){
hello.x=hello.x+1;
hello.setLocation(hello.x,hello.y);
repaint();
}
if(e.getKeyCode() == KeyEvent.VK_SPACE){
goingon = true;
repaint();
}
}
@Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_SPACE){
goingon = false;
repaint();
}
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
Don't forget to call
super.paintComponent()
in overriddenpaintComponent()
method that clears the previews view.Read more...