xxxxxxxxxx
49
let oscillators = [];
function setup() {
createCanvas(560,390);
//initialize all objects
for (let i = 0; i < 10; i++) {
oscillators.push(new Oscillator());
}
}
function draw() {
background(220);
// run all objects
for (let i = 0; i < oscillators.length; i++) {
oscillators[i].oscillate();
oscillators[i].display();
}
}
class Oscillator {
constructor() {
//track two angles
this.angle = createVector();
//random velocities, we need two angular velocities
this.velocity = createVector(random(-0.05, 0.05), random(-0.05, 0.05));
//random amplitudes, we need two amplitudes (for x-axis and y-axis)
this.amplitude = createVector(random(20, width/2), random(20, height/2));
}
oscillate() {
this.angle.add(this.velocity);
}
display() {
//oscillating on x-axis and y-axis
let x = sin(this.angle.x) * this.amplitude.x;
let y = sin(this.angle.y) * this.amplitude.y;
push();
translate(width/2, height/2);
stroke(50);
strokeWeight(2);
fill(63,63,147,200);
line(0, 0, x, y); //drawing Oscillator as a line connecting a circle
ellipse(x, y, 32, 32);
pop();
}
}