Loading...
Logo
Processing Forum
My program has 3 files -  a main, an avatar class that creates the player, and an opponent class that creates the opponent.

I want my avatar and opponent to be able to fire bullets. At first I thought about created a separate bullet class and pass in the vector locations of the player/opponent but that didn't work.

class Bullet{
      PVector pos;

      void draw(){
            ellipse(pos.x, pos.y, 10, 10);
      }

      void getLoc(PVector a){
            pos.x=a.x;
            pos.y=a.y;
      }
}

Then in main I had

Bullet fire;
fire=new PVector();

if ( key == ' ' ) {
    fire.getLoc( player.getPos() );
  }

I kept getting a null pointer exception. Anyone got any other ideas about how I can implement the bullet?

Replies(3)

Assuming you want to do it in a class:

class Bullet{
      PVector pos;

      Bullet(PVector a)
      {
            pos = new PVector(a.x, a.y);
      }


      void draw(){
            ellipse(pos.x, pos.y, 10, 10);
      }
}

To make a bullet:

Bullet fire = new Bullet(player.getPos());

You will still need to add code to make the bullet move, from frame to frame.
From main.

void draw(){
    if(keys[4]) fire.draw();
}

keys being the array where I store which keys are pressed and 4 is for space bar.

void keyPressed(){
  if ( key == ' ') {
    keys[4]=true;
    fire = new Bullet( player.getPos() );
  }
}

I made the bullet move but how can I make it so that it will continue to go on till it either hits the edge of the screen or an enemy. Right now the bullet resets itself every time I hit space bar again or when I hold on to it.

void draw(){
    fill( #abcdef );
    stroke( #abcdef );
    ellipseMode( CORNER );
    ellipse(pos.x+10, pos.y, 10, 10);
    pos.y-=5;
}

The draw for the bullet class.
Two solutions: either you check the fire state when checking for a new bullet: if still moving / visible, don't fire a new one. Or you put the bullets in an array list and iterate on the list to display / manage them all. This would allow to have several bullets at one time.