xxxxxxxxxx
134
//Jessie Zhai
//NOC - Week4
class Ege {
constructor() {
this.mass = 1;
this.position = createVector(width/2, 30);
this.velocity = createVector(0, 0);
this.acceleration = createVector(0, 0);
this.rotation = 0;
this.hasRotated = false;
}
applyForce(force) {
let f = p5.Vector.div(force, this.mass);
this.acceleration.add(f);
}
update() {
this.velocity.add(this.acceleration);
this.position.add(this.velocity);
this.acceleration.mult(0);
}
checkWaveIntersection(allWaves) {
let totalWaveY = 0;
for (let waveSet of allWaves) {
for (let wave of waveSet) {
totalWaveY += wave.calculate(this.position.x);
}
}
totalWaveY += 300;
let threshold = 5;
if (!this.hasRotated && abs(this.position.y - totalWaveY) < threshold) {
this.hasRotated = true;
this.rotation = HALF_PI;
}
}
display() {
push();
translate(this.position.x, this.position.y);
rotate(this.rotation);
image(egeimg, -egeimg.width/2, -egeimg.height/2);
pop();
}
}
class Wave {
constructor(amp, period, phase) {
this.amplitude = amp;
this.period = period;
this.phase = phase;
}
calculate(x) {
return sin(this.phase + TWO_PI * x/this.period) * this.amplitude;
}
}
let waves = [];
let egeimg;
let ege;
let waveColors = ["lightblue", "rgb(20, 0, 255)", "rgb(55, 180, 200)"];
let waveSpeeds = [0.08, 0.06, 0.04];
let waveParams = [
{amp: [10, 20], period: [100, 600]},
{amp: [8, 15], period: [80, 400]},
{amp: [5, 12], period: [60, 300]}
];
function preload() {
egeimg = loadImage('ege.png');
}
function setup() {
createCanvas(500, 400);
ege = new Ege();
for (let i = 0; i < 3; i++) {
waves[i] = [];
for (let j = 0; j < 5; j++) {
waves[i][j] = new Wave(
random(waveParams[i].amp[0], waveParams[i].amp[1]),
random(waveParams[i].period[0], waveParams[i].period[1]),
random(TWO_PI)
);
}
}
egeimg.resize(0, 70);
}
function draw() {
background(0, 20);
fill("white");
text('Click mouse to save Ege', width/2 -50, 20);
let gravity = createVector(0, 0.005);
ege.applyForce(gravity);
if (mouseIsPressed) {
let up = createVector(0, -0.1);
ege.applyForce(up);
}
ege.update();
ege.checkWaveIntersection(waves);
ege.display();
for (let i = 0; i < waves.length; i++) {
for (let x = 0; x < width; x += 1) {
let y = 0;
for (let wave of waves[i]) {
y += wave.calculate(x);
}
noStroke();
fill(waveColors[i]);
ellipse(x, y + 300, 1);
}
}
for (let i = 0; i < waves.length; i++) {
for (let wave of waves[i]) {
wave.phase += waveSpeeds[i];
}
}
}