Skip to content

Instantly share code, notes, and snippets.

@Mobilpadde
Created October 25, 2019 20:46
Show Gist options
  • Save Mobilpadde/76b5450149e95aa91962ad3be2324c3e to your computer and use it in GitHub Desktop.
Save Mobilpadde/76b5450149e95aa91962ad3be2324c3e to your computer and use it in GitHub Desktop.
var Ball = function Ball() {
this.loc = createVector(width / 2, height / 2);
this.vel = createVector();
this.acc = createVector();
this.col = color(random(55, 200));
this.sz = random(10, 25);
this.mass = this.sz * 1.5;
}
Ball.prototype.addForce = function addForce(force) {
var f = p5.Vector.div(force, this.mass);
this.acc.add(f);
}
Ball.prototype.move = function move() {
this.vel.add(this.acc);
this.vel.limit(1);
this.loc.add(this.vel);
this.acc.mult(0);
}
Ball.prototype.keepInView = function keepInView() {
this.loc.x = constrain(this.loc.x, 0, width);
this.loc.y = constrain(this.loc.y, 0, height);
}
Ball.prototype.draw = function draw() {
fill(this.col);
ellipse(this.loc.x, this.loc.y, this.sz, this.sz);
}
var Arrow = function Arrow(w) {
this.wind = w;
var fake = this.wind.copy();
fake.y *= -1;
this.loc = p5.Vector.sub(fake, createVector());
this.loc.normalize()
}
Arrow.prototype.setWind = function setWind(w) {
this.wind = w.copy();
}
Arrow.prototype.draw = function draw() {
push();
translate(width / 2 + this.loc.x, height / 2 + this.loc.y);
fill(255);
rotate(atan2(this.loc.x, this.loc.y));
ellipse(this.loc.x, this.loc.y, 10, 10)
triangle(
this.loc.x + 5, this.loc.y + 0,
this.loc.x - 5, this.loc.y + 0,
this.loc.x + 0, this.loc.y - 10
);
triangle(
0, -width / 2 + width / 64,
10, -width / 2 + width / 64,
5, -width / 2
);
pop();
var fake = this.wind.copy();
fake.y *= -1;
fake.normalize();
var to = p5.Vector.sub(fake, createVector());
this.loc.lerp(to, 0.02);
}
var Wind = function Wind() {
this.wind = null;
this.update(0);
}
Wind.prototype.update = function update(a) {
this.wind = p5.Vector.fromAngle(a);
}
Wind.prototype.get = function get() {
return this.wind;
}
var balls = [];
var wind = null;
function setup() {
const c = createCanvas(685, 685);
c.parent("sample");
balls = new Array(2).fill(0).map(() => new Ball());
wind = new Wind()
arrow = new Arrow(wind.get());
noStroke();
}
function draw() {
background(25);
if (frameCount % 100 === 0) {
var windDir = random(0.0, 1.0) * 2 * Math.PI;
wind.update(windDir);
arrow.setWind(wind.get());
}
balls.forEach((b) => {
b.addForce(wind.get());
b.move();
b.keepInView();
b.draw();
})
arrow.draw();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment