Siirry suoraan sisältöön

Javascript – partikkelit

  • tehnyt

Live demo täällä: https://pulustudio.com/connecting_particles/

let space_w = window.innerWidth-2;
let space_h = window.innerHeight-2;
recalc_fps = 0;
fps=1;
let a = [];
let asteroid_count = 200;
let cosmic_speed_limit = 7;
function setup() {
    createCanvas( space_w, space_h);
    background(”#000”);
    frameRate(30);
    for (i = 0; i < asteroid_count; i++ ) {
        a[i] = new Asteroid( i, Math.random()*cosmic_speed_limit );
    }
}
function draw() {
    background(0);
    for (i = 0; i < asteroid_count; i++ ) {
        a[i].move();
        a[i].draw();
    }
    update_fps();
}
function update_fps() {
    recalc_fps++;
    recalc_fps %= 30;
    if (recalc_fps === 0) fps =  Math.floor(frameRate());
    text( fps + ” fps”, 20,30);
}

// asteroid.js

class Asteroid {
    id;
    location_x;
    location_y;
    location_z;
    size;
    color;
    lonely = false;
    bounces = false;
    v = p5.Vector(0,0);
    constructor( _id, maxspeed ) {
        this.id = _id;
        this.location_x = Math.random() * space_w;
        this.location_y = Math.random() * space_h;
        this.v = new p5.Vector( Math.random() * maxspeed – maxspeed/2, Math.random() * maxspeed – maxspeed/2);
        this.size = 1+ Math.floor( Math.random() * 5);
        this.color = ”#aaa”;
       // if (this.size < 1.4) this.lonely = true;
       if (this.size>3) this.bounces=true;
    }
    move() {
        this.location_x += this.v.x;
        this.location_y += this.v.y;
        if (this.bounces) {
            if (this.location_x > space_w) this.v.x = -this.v.x;
            if (this.location_x < 0) this.v.x = -this.v.x;
            if (this.location_y > space_h) this.v.y = -this.v.y;
            if (this.location_y < 0) this.v.y = -this.v.y;
        }
        else {
            if (this.location_x > space_w) this.location_x = 0;
            if (this.location_x < 0) this.location_x = space_w;
            if (this.location_y > space_h) this.location_y = 0;
            if (this.location_y < 0) this.location_y = space_h;
        }
    }
    draw() {
        fill(this.color);
        ellipse(this.location_x, this.location_y, this.size);
        if (!this.lonely) {
            for( var ai = 0; ai < asteroid_count; ai++) {
                if ( ai != this.id && !a[ai].lonely) {
                    let distance = dist(a[ai].location_x, a[ai].location_y, this.location_x, this.location_y );
                    if (distance < 130) {
                        strokeWeight(1);
                        stroke(0,  140-distance, distance*0.1);
                        line( this.location_x, this.location_y, a[ai].location_x, a[ai].location_y);
                    }
                }
            }
        }
    }
}
Avainsanat: