Click to fire a bullet. Hold to fire multiple bullets.
Bullets will fire in the direction of the pointer.
/* @pjs preload="bullet.png"; */ PImage bullet; int bullet_x; int bullet_y; float bullet_rotation; // 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); //Draw images from center imageMode(CENTER); // 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); } } // 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(); } // Aim the gun at the pointer. bullet_rotation = atan2(mouseY-bullet_y, mouseX-bullet_x); for(Bullet b : bullets){ b.update(); b.display(); } // Create an object representing our gun pushMatrix(); translate(bullet_x, bullet_y); rotate(bullet_rotation); image(bullet, 0, 0); popMatrix(); } 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); b.rotation = bullet_rotation; b.x_velocity = cos(b.rotation) * BULLET_SPEED; b.y_velocity = sin(b.rotation) * BULLET_SPEED; break; } } } // Detects a single mouseclick void mousePressed(){ // Shoot a bullet //shootBullet(); } class Bullet{ int x; int y; float x_velocity; float y_velocity; boolean alive; PImage img; float rotation; Bullet(PImage img){ this.img = img; } void display(){ if(alive){ pushMatrix(); translate(x,y); rotate(rotation); image(img, 0, 0); popMatrix(); } } void update(){ if(alive){ x += x_velocity; y += y_velocity; // Bullets should kill themselves when they leave the world. if(x > width || x < 0 || y > height || y < 0){ kill(); } } } void revive(){ alive = true; } void reset(int x, int y){ this.x = x; this.y = y; } void kill(){ alive = false; } }