Wednesday, 20 March 2019

p5-EXPLOSIONS

I love Wireframe magazine, mainly because it seems like a blast from the past where I eagerly bought the latest ZX Spectrum magazine for the game listing... then spent hours upon hours entering the code into the machine to play a game. I know there were often bugs, but the debugging was sometimes the best part. I know I'm not alone in this as at least Ben Collins joins me in an appreciation of debugging.

Where I'm sort of sad though is that most of the smaller listings are in Python and, while I can find my way around Python, I much prefer JS, so I've started converting the listings to JS using p5. I've translated the Parallax example from issue 3, but the one above (from issue 1) was the most challenging yet as I needed to re-architect the program to work with p5. It wasn't all that hard really, but it was fun, especially getting my head around the trigonometry.

This is the JS code, should you want to enter it yourself:

const width = 800;
const height = 400;
const drag = 0.8;
const particles = [];
const framerate = 10;
const speed = 60;

const explode = () => {
    const x = random(width);
    const y = random(height);
    for (var i = 0; i < 100; i++) {
        particles.push({
            x, 
            y, 
            vx: speed * pow(random(1), 0.5) * sin(random(2 * PI)), 
            vy: speed * pow(random(1), 0.5) * cos(random(2 * PI)), 
            age: 0, 
            birth: new Date()
        });
    }
}

function setup() {
    createCanvas(width, height);
    stroke(255, 230, 128);
    frameRate(framerate);
    explode();
}

function draw() {
    if (frameCount % 10 === 0) {
        explode();
    }
    clear();
    background(0);
    particles.forEach(function(p, index, arr) {
        if (p.age <= 2) {
            const age = new Date().getSeconds() - p.birth.getSeconds();
            point(p.x, p.y);
            p.x = p.x += p.vx * p.age;
            p.y = p.y += p.vy * p.age;
            p.vx = p.vx * Math.pow(drag, p.age);
            p.vy = p.vy * Math.pow(drag, p.age);
            p.age = age;
        }else{
            arr.splice(index, 1);
        }
    });
}

No comments:

Post a Comment