Skip to content

Instantly share code, notes, and snippets.

@alkemann
Last active March 5, 2017 00:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alkemann/46bc96aa38ff879a3c9bea1799b60606 to your computer and use it in GitHub Desktop.
Save alkemann/46bc96aa38ff879a3c9bea1799b60606 to your computer and use it in GitHub Desktop.
P5.js with Matter.js .. click and hold to drop balls of various sizes
const engine = Matter.Engine.create(),
ground = new Ground(x = 200, y = 360, w = 600, h = 50, a = 0.2),
shelf = new Ground(x = 250, y = 150, w = 200, h = 30, a = -0.2);
var bodies = [], lastFrame, rad = 2;
function setup() {
createCanvas(400, 400);
frameRate(60);
stroke(200);
fill(150);
engine.world.bounds = {min: {x: -200, y: -200}, max: {x: width+200, y: height+200}};
}
function draw() {
const now = millis();
const deltaTime = (now - lastFrame);
lastFrame = now;
Matter.Engine.update(engine, deltaTime);
background(50);
ground.show();
shelf.show();
bodies.forEach((b) => b.show());
if (mouseIsPressed) {
rad = (rad > 100) ? rad : rad + 1;
ellipse(mouseX, mouseY, rad * 2, rad * 2);
}
if (frameCount % 30 === 0) {
bodies.push(new Ball(300, 50, random(4, 20)));
}
if (frameCount % 60 === 0) { // clean out dead balls once a second
bodies = bodies.filter((b) => b.body.position.y < (height + 100));
engine.world.bodies = engine.world.bodies.filter((b) => b.position.y < (height + 100));
}
}
function mouseReleased() {
bodies.push(new Ball(mouseX, mouseY, rad));
rad = 2; // reset rad
}
function Ball(x, y, r) {
const o = { friction: 0.7, restitution: 0.5, density: 100};
this.body = Matter.Bodies.circle(x, y, r, o);
Matter.World.add(engine.world, this.body);
this.d = r * 2;
}
Ball.prototype.show = function() {
push();
translate(this.body.position.x, this.body.position.y);
rotate(this.body.angle);
ellipse(0, 0, this.d);
stroke(20, 200, 200, 100);
line(0, 0, 0, this.d * 0.5);
pop();
}
function Ground(x, y, w, h, a) {
const o = { friction: 0.9, restitution: 0.9, isStatic: true, angle: a}
Matter.World.add(engine.world, Matter.Bodies.rectangle(x, y, w, h, o));
this.show = function() {
push();
noStroke(); fill(10);
rectMode(CENTER);
translate(x, y); rotate(a);
rect(0, 0, w, h);
pop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment