xxxxxxxxxx
112
// Daniel Shiffman tutorial
// http://codingtra.in
// http://patreon.com/codingtrain
// Code for: https://youtu.be/urR596FsU68
// Daniel Shiffman
// Matter.js + p5.js Examples
// This example is based on examples from: http://brm.io/matter-js/
var Engine = Matter.Engine,
//Render=Matter.Render,
World = Matter.World,
Bodies = Matter.Bodies,
Constraint = Matter.Constraint,
Mouse = Matter.Mouse,
mouseConstraint = Matter.MouseConstraint;
//variables.
var engine;
var boxA;
var world;
var particles = [];
var ground;
var boundaries = [];
var mConstraint;
function setup() {
var canvas = createCanvas(500, 500);
background(0);
// create an engine
engine = Engine.create();
world = engine.world;
// run the engine
Engine.run(engine);
var prev = null;
for (var x = 200; x < 400; x += 20) {
var fixed = false;
if (!prev) {
fixed = true; //make first one static
}
//circles
var p = new Particle(x, 100, 15, fixed);
//var p2 = new Particle(200, 150, 10);
//push into the array
// particles.push(p1, p2);
particles.push(p);
if (prev) {
var options = {
bodyA: p.body,
bodyB: prev.body,
length: 50,
stiffness: 0.4
}
var constraint = Constraint.create(options);
World.add(world, constraint); //put int he world.
}
prev = p;
}
//grounds
boundaries.push(new Boundary(250, height - 10, width, 50));
var canvMouse = Mouse.create(canvas.elt);
canvMouse.pixelRatio = pixelDensity(); //built in P5 function for high retina displays.
var optionsM = {
mouse: canvMouse
}
mConstraint = mouseConstraint.create(engine, optionsM);
World.add(world, mConstraint);
}
// function mouseDragged() {
// circles.push(new Circle(mouseX, mouseY, random(10, 40)));
// }
function draw() {
background(0);
Engine.update(engine);
//particles.push(new Circle(100, 50, random(10, 20)));
for (var i = 0; i < particles.length; i++) {
particles[i].show();
//removal check
// if (particles[i].isOffScreen()) {
// particles[i].removeFromWorld(); //remove from Matter.js
// particles.splice(i, 1); //remove from array
// i--;
// }
}
//visual of ground(not needed to make it function);
for (var j = 0; j < boundaries.length; j++) {
boundaries[j].show();
}
//if click on body with mouse display something
if (mConstraint.body) {
var pos = mConstraint.body.position;
var offset=mConstraint.constraint.pointB;//offset to actual mouse pos.
var m =mConstraint.mouse.position
//draw a line where its connected via mouse.
stroke(0, 255, 0);
line(pos.x+offset.x, pos.y+offset.y,m.x,m.y);
}
}