Forces
This week in The Nature of Code I learned about techniques for simulating forces in P5.js using vectors and principles from physics.
In brainstorming for this assignment the indie game LIMBO was a strong inspiration for the look and feel.
Expanding on the in class demo of Gravitational Attraction I set out to write a sketch reminiscent of planets orbiting a star. This sketch uses the WEBGL renderer to generate a pulsing “star” from point lights on a plane in the middle of the screen. Clicking on the canvas generates planet objects that are attracted to the star at the center. To emulate the fall-off characteristics of light on the planets their brightness values are calculated based on their distance from the center.
An additional function called collisionCheck() loops through the planets array and combines planet objects when a collision is detected.
function collisionCheck(i){ // Collision // confirm there are more than one planet object if(planets.length > 1){ for(let a = i+1; a < planets.length; a++){ let distance = p5.Vector.dist(planets[a].pos, planets[i].pos); // check that planets objects are touching if(distance < planets[a].r + planets[i].r){ // combine two objects in array planets[a].vel = p5.Vector.add(planets[a].vel, planets[i].vel); planets[a].vel.div(2); planets[a].acc = p5.Vector.add(planets[a].acc, planets[i].acc); planets[a].acc.div(2); // combine mass of two objects planets[a].mass += planets[i].mass; // approximate math for calculating new radius planets[a].r = (planets[i].r + planets[a].r)/1.7; // play tone planets[a].env.play(); // delete second object from array planets.splice(i, 1); } } } }
In this sketch planet objects generate a tone. When a planet object is first created it is randomly assigned a frequency from the preset scale array based on the Lydian Mode G Scale. Passing close enough to the star attractor at the center of screen or colliding with another planet object also triggers tone playback.
I have hidden some other functions into the sketch below! Touch is enabled as well so it will run on a smartphone or tablet.