How to create (spawn) several rectangles?

2

I'm creating a Jframe game where I need to create multiple rectangles that will be the projectiles / bullets of my main / I created the following class:

Class Bullets

package dannark;

import java.awt.Color;
import java.awt.Graphics;

public class balas {
    int x,y,lar,alt;
    String dir;

    public balas(int x, int y, int lar, int alt, String dir){
        this.x = x;
        this.y = y;
        this.lar = lar;
        this.alt = alt;
        this.dir = dir;
    }

    public void draw(Graphics bbg){
        if(dir.equals("right")){
            x += 10;
        }else{
            x -= 10;
        }
        bbg.setColor(Color.yellow);
        bbg.fillRect(main.camX+x,  main.camY+y, lar, alt);
    }
}

More like I can call it in my main class so that when I press the C button it always shoots a new ball?

Main Class

public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == e.VK_C){
            //o que fazer aqui para spawnar varios novos retangulos?
        }

    }
    
asked by anonymous 25.06.2014 / 17:35

1 answer

1

Hey guys, I was able to figure out a solution, just use an arraylist to store my various instances of my same class. This site here helped me: link

In other words, I created the array:

   ArrayList<balas> bala = new ArrayList();  

2nd Then I saved the instances inside the array

  if(shoot){
      bala.add(new balas(x,y-25,6,3,direcao)); // instancia um novo Objeto e salvo na array
  }

3rd And to take the value of each was just to do so:

  for(int i = 0; i < bala.size(); i++){
      bala.get(i).draw(main.bbg);
  }

The result was:

    
25.06.2014 / 20:10