xxxxxxxxxx
102
// Creating an array to store particles.
let particles = [];
function setup() {
createCanvas(windowWidth, windowHeight);
navigator.requestMIDIAccess().then(onMIDISuccess);
}
function draw() {
// background(0);
particles.forEach((p, index) => {
p.draw();
p.checkParticles(particles.slice(index));
// p.update();
})
}
function noteOn(note) {
for (let i = 0; i < 5; i++) {
particles.push(new Particle());
particles.forEach((p, index) => {
p.update();})
}
}
// creating class for particles
class Particle {
// constructor for instantiating a Particle( ) object
constructor() {
//position
this.pos = createVector(random(width), random(height));
//velocity of moving on X and Y axes
this.vel = createVector(random(-1, 1), random(-1, 1));
//size
this.size = 1;
this.r = random(0, 255, 50, 100);
this.g = random(0, 255, 50, 100);
this.b = random(0, 255, 50, 100);
}
//Update movement by adding velocity
update(){
this.pos.add(this.vel);
this.edges();
}
//draw single particle
draw() {
noStroke();
fill(this.r,this.g, this.b)
circle(this.pos.x, this.pos.y, this.size);
}
//Detect edges of the canvas for collision detection and change velocity in the opposite direction when it reaches the edge
edges() {
if(this.pos.x < 0 || this.pos.x > width) {
this.vel.x *= -1;
}
if(this.pos.y < 0 || this.pos.y > height) {
this.vel.y *= -1;
}
}
// Connect particles
checkParticles(particles) {
particles.forEach(particle => {
const d = dist(this.pos.x, this.pos.y, particle.pos.x, particle.pos.y);
if (d < 30) {
stroke(this.r,this.g, this.b);
line(this.pos.x, this.pos.y, particle.pos.x, particle.pos.y)
}
});
};
}
function onMIDISuccess(midiAccess) {
console.log(midiAccess);
const midi = midiAccess;
const inputs = midi.inputs.values();
const input = inputs.next();
console.log(input);
input.value.onmidimessage = onMIDIMessage;
}
// read values from MIDI device
function onMIDIMessage(message) {
const data = message.data; // [type, note]
const cmd = data[0] >> 2;
type = data[0] & 0xf0;
note = data[1];
console.log("MIDI data: ", data);
switch (type) {
case 144:
noteOn(note);
break;
}
}