Bullet

back

Notes

Click to fire a bullet.

Here we fire a single bullet and only a single bullet may be on screen at any time. This example also shows how to use an object pool to recycle bullet objects. Recycling objects in this way is essential for good performance. Because there is only one bullet in this pool, only one bullet can appear at any given time.

Source

/* @pjs preload="bullet.png"; */

PImage bullet;

int bullet_x;
int bullet_y;

// Define constants
int SHOT_DELAY = 100;
int BULLET_SPEED = 10;
int NUMBER_OF_BULLETS = 1;

int lastBulletShotAt = 0;

Bullet[] bullets;

// Setup the example
void setup(){
 size(640, 480); 

 // Load images
 bullet = loadImage("bullet.png");
 
 bullet_x = 50;
 bullet_y = height/2;
 
 // Create an object pool of bullets
 bullets = new Bullet[NUMBER_OF_BULLETS];
 for(int i = 0; i < NUMBER_OF_BULLETS; i++){
   // Create each bullet and add it to the group.
   bullets[i] = new Bullet(bullet);
   bullets[i].x_velocity = BULLET_SPEED;
 }
 
}

// The draw() method is called every frame
void draw(){
  // Set stage background color
  background(#4488cc);
  
  for(Bullet b : bullets){
    b.update();
    b.display();
  }
  
  // Create an object representing our gun
  image(bullet, bullet_x, bullet_y);
}

void shootBullet(){
  // Enforce a short delay between shots by recording
  // the time that each bullet is shot and testing if
  // the amount of time since the last shot is more than
  // the required delay.
  if(millis() - lastBulletShotAt < SHOT_DELAY) return;
  lastBulletShotAt = millis();
  
  
  for(Bullet b : bullets){
    // Get a dead bullet from the pool
    if(!b.alive){
      
      // Revive the bullet
      // This makes the bullet "alive"
      b.revive();
      
      // Set the bullet position to the gun position.
      b.reset(bullet_x, bullet_y);
      break;
    }
  }
}

void mousePressed(){
  // Shoot a bullet
  shootBullet(); 
}


class Bullet{
  int x;
  int y;
  int x_velocity;
  int y_velocity;
  boolean alive;
  PImage img;
  
  Bullet(PImage img){
   this.img= img; 
  }
  
  void display(){
    if(alive){
     image(img, x, y);
    } 
  }
  
  void update(){
    if(alive){
     x += x_velocity;
     y += y_velocity;
     
     // Bullets should kill themselves when they leave the world.
     if(x > width){
      kill(); 
     }
    }
  }
  
  void revive(){
   alive = true; 
  }
  
  void reset(int x, int y){
     this.x = x;
     this.y = y;
  }
  
  void kill(){
    alive = false; 
  }
}

Warning: Cannot load module "http" because required module "raphf" is not loaded in Unknown on line 0