New Orbital Sketch

This last week we learned a few things that made me reconsider how I might be able to improve older sketches I wrote. I decided to look at my old Orbiting Bodies sketch to see if I could somehow make it simpler.

Initially, I used a code that had a list of attributes associated with each of the orbiting particles. These attributes included mass, orbital radius, velocity, etc. And I had a loop in the setup portion of the sketch that went through and input a random value in each one of the variables. When I wanted to add a new particle, I had to copy that code and append values at the end of each of the arrays, which felt odd or inefficient.

I now am using classes, which has a special constructor function that is run the first time a new class is added to an array. This was a perfect analog for what I was essentially faking previously. I’m still figuring a couple of things out, but I was able to completely recreate the effect in a much simpler way.

If I have more time, I’ll break out the display function in the class into a move and display which feels a bit more controlled. I will also try to create some more interesting effects in the way that the trails are made. Code below!

let satellites = [];
let n = 500;
let fC = 200; //our version of the time counter. Starting at 200 gets all the satellites scattered.

function setup() {
createCanvas(800, 800);

for (i = 0; i < n; i += 1) {
satellites[i] = new Orbit(1,1);
}
}

function draw() {
background(0, 50);
//translate(width / 2 - mouseX, 0); //camera pan based on mouseX location
for (i = 0; i < satellites.length; i += 1) {
satellites[i].display(fC);
}

fC += 0.03;

}

function mousePressed() {
if (mouseButton == LEFT) {
satellites.push(new Orbit(4,3));
}
}

class Orbit {
constructor(r,s) {
this.red1 = r; //this is just sent an argument when mouse pressed
this.speed1 = s;
this.mass = random(5);
this.radius = random(width * 0.3, width * 0.5);
this.speed = this.speed1 * sqrt(this.mass / this.radius * 3);

this.shade = random(0, 100);
this.red = this.red1 * this.shade;
}

display(fC) {
this.fC = fC;
this.aY = (this.radius / 2 - (mouseY / height) * this.radius);
strokeWeight(this.mass * (sin(this.speed * this.fC * PI / 2 + PI / 2) + 2) / 2);