Click to fire a bullet. Hold to fire multiple bullets.
We can enable rapid fire simply by increasing the number of available bullets in the array.
/* @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 = 20; 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); // Detects if mousebutton is down if(mousePressed){ // Shoot a bullet shootBullet(); } 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; } } } // Detects a single mouseclick 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; } }