Skip to content

Instantly share code, notes, and snippets.

@rampol
Created June 23, 2018 15:34
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 rampol/70e6132b686af8bb0d5072afa3af4207 to your computer and use it in GitHub Desktop.
Save rampol/70e6132b686af8bb0d5072afa3af4207 to your computer and use it in GitHub Desktop.
Playing with Matter
// Matter module aliases
var Engine = Matter.Engine,
World = Matter.World,
Body = Matter.Body,
Bodies = Matter.Bodies,
Constraint = Matter.Constraint,
Composites = Matter.Composites,
MouseConstraint = Matter.MouseConstraint;
// create a Matter.js engine
var engine = Engine.create(document.body, {
render: {
options: {
wireframes: false,
background: '//s3-us-west-2.amazonaws.com/s.cdpn.io/28963/ball-bk2.jpg'
}
}
});
// add a mouse controlled constraint
var mouseConstraint = MouseConstraint.create(engine);
World.add(engine.world, mouseConstraint);
// some settings
var offset = 30,
wallOptions = {
isStatic: true
};
// add some invisible some walls to the world
World.add(engine.world, [
Bodies.rectangle(400, -offset, 800 + 2 * offset, 50, wallOptions),
Bodies.rectangle(400, 600 + offset, 800 + 2 * offset, 50, wallOptions),
Bodies.rectangle(800 + offset, 300, 50, 600 + 2 * offset, wallOptions),
Bodies.rectangle(-offset, 300, 50, 600 + 2 * offset, wallOptions)
]);
//create a stack
var stack = Composites.stack(6, 6, 12, 4, 0, 0, function(x, y, column, row) {
if (Math.random() > 0.5) {
return Bodies.rectangle(x, y, 64, 64, {
render: {
sprite: {
texture: '//s3-us-west-2.amazonaws.com/s.cdpn.io/28963/box-grape-blue.png'
}
}
});
} else if (Math.random() > 0.9) {
return Bodies.rectangle(x, y, 64, 64, {
render: {
sprite: {
texture: '//s3-us-west-2.amazonaws.com/s.cdpn.io/28963/box-grape-red.png'
}
}
});
} else if (Math.random() > 0.7) {
return Bodies.circle(x, y, 46, {
density: 0.0005,
frictionAir: 0.06,
restitution: 0.3,
friction: 0.06,
render: {
sprite: {
texture: '//s3-us-west-2.amazonaws.com/s.cdpn.io/28963/ball-grape-green.png'
}
}
});
} else {
return Bodies.circle(x, y, 46, {
density: 0.0005,
frictionAir: 0.06,
restitution: 0.3,
friction: 0.06,
render: {
sprite: {
texture: '//s3-us-west-2.amazonaws.com/s.cdpn.io/28963/ball-grape.png'
}
}
});
}
});
// add the stack to the world
World.add(engine.world, stack);
// run the engine
Engine.run(engine);
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.12.0/matter.min.js"></script>
body {
background: #111;
text-align: center;
}
canvas {
display: inline-block;
max-width: 100%;
max-height: 300px;
}
canvas:active {
cursor: pointer;
cursor: grabbing;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment