Skip to content

Instantly share code, notes, and snippets.

@tonyhschu
Last active July 23, 2017 21:01
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 tonyhschu/9289d83eae605352ce53396b1e60efca to your computer and use it in GitHub Desktop.
Save tonyhschu/9289d83eae605352ce53396b1e60efca to your computer and use it in GitHub Desktop.
Matterjs Trial
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.12.0/matter.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<script>
// module aliases
var Engine = Matter.Engine,
Render = Matter.Render,
Runner = Matter.Runner,
World = Matter.World,
Bodies = Matter.Bodies;
// create an engine
var engine = Engine.create();
// create a renderer
var render = Render.create({
element: document.body,
engine: engine,
options: {
width: 960,
height: 500
}
});
Render.lookAt(render, {
min: { x: 0, y: 0 },
max: { x: 960, y: 500 }
});
Render.run(render);
let ballRadius = 2
let dividerWidth = 2
let dividerOffset = ballRadius * 2.5 + dividerWidth
// create two boxes and a ground
var boxA = Bodies.rectangle(400, 200, 80, 80);
var boxB = Bodies.rectangle(450, 50, 80, 80);
var ground = Bodies.rectangle(480, 500, 960, 20, { isStatic: true });
// Create Bin Edges
var dividers = d3.range(Math.floor(960 / dividerOffset)).map(function(i) {
let div = Bodies.rectangle(i * dividerOffset, 450, 3, 100);
Matter.Body.setStatic(div, true);
return div
})
let gap = ballRadius * 4
let vgap = 12
var rows = d3.range(Math.floor(200 / 7)).forEach(function(j) {
var pins = d3.range(Math.floor(960 / 7)).map(function(i) {
let offset = (j % 2 > 0) ? 0 : gap / 2
let x = i * gap + offset + 2
let y = 50 + j * vgap
let pin = Bodies.circle(x, y, 1);
Matter.Body.setStatic(pin, true);
return pin
})
World.add(engine.world, pins);
})
// add all of the bodies to the world
World.add(engine.world, [ground]);
World.add(engine.world, dividers);
// run the engine
var runner = Runner.create({
delta: 1000 / 60,
isFixed: false,
enabled: true
});
var addBall = function() {
circle = Bodies.circle(479 + 2 * Math.random(), 10, ballRadius)
Matter.Body.setMass(circle, 0.1)
World.add(engine.world, [circle])
}
var frame = 0
var running = false
var gameloop = function() {
running = true
window.requestAnimationFrame(gameloop);
Engine.update(engine, 1000 / 60);
frame = (frame + 1) % 4;
if (frame === 0) {
addBall()
}
}
gameloop();
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment