<section class="shapes">
<!-- all my matter.js project here -->
</section>
<!-- <section class="split"></section> -->
<script src="matter.min.js"></script>
<script src="shapes.js"></script>
body {
margin: 0;
padding: 0;
}
// two things matter needs
// first thing is an engine - the computation and math behind this
// second thing is a renderer - this draws the engine
// alias to make the code cleaner
// const Engine = Matter.Engine
// const Render = Matter.Render
const {Engine, Render, Bodies, World, MouseConstraint, Composites} = Matter
// where is matter being deployed?
const sectionTag = document.querySelector("section.shapes")
// what is the w and h of the page?
const w = window.innerWidth
const h = window.innerHeight
const engine = Matter.Engine.create()
const renderer = Matter.Render.create({
element: sectionTag,
engine: engine,
options: {
height: h,
width: w,
background: "blue",
wireframes: false,
pixelRatio: window.devicePixelRatio
}
})
// have the ability to create a brand new shape
const createShape = function (x, y) {
return Bodies.circle(x, y, Math.min(30, 30), {
render: {
sprite: {
texture: "http://tetlow.superhi.com/tetlow.png",
xScale: 0.15,
yScale: 0.15,
}
}
})
}
const bigBall = Bodies.circle(w / 2, h / 2, Math.min(w/4, h/4), {
isStatic: true,
render: {
fillStyle: "red",
}
})
const wallOptions = {
isStatic: true,
render: {
visible: false,
}
}
const ground = Bodies.rectangle(w / 2, h + 50, w + 100, 100, wallOptions)
const ceiling = Bodies.rectangle(w / 2, -50, w + 100, 100, wallOptions)
const leftWall = Bodies.rectangle(-50, h / 2, 100, h + 100, wallOptions)
const rightWall = Bodies.rectangle(w + 50, h / 2, 100, h + 100, wallOptions)
const mouseControl = MouseConstraint.create(engine, {
element: sectionTag,
constraint: {
render: {
visible: false,
}
}
})
const initialShapes = Composites.stack(50, 50, 15, 5, w / 15, 40, function (x, y) {
return createShape(x, y)
})
World.add(engine.world, [
bigBall,
ground,
ceiling,
leftWall,
rightWall,
mouseControl,
initialShapes,
])
// when we click the page add a new shape
document.addEventListener("click", function (event) {
const shape = createShape(event.pageX, event.pageY)
World.add(engine.world, shape)
})
// run both the engine and the renderer
Engine.run(engine)
Render.run(renderer)
let time = 0
const changeGravity = function () {
time = time + 0.005
const gravity = Math.cos(time)
engine.world.gravity.y = gravity
requestAnimationFrame(changeGravity)
}
changeGravity()
// // mobile responsiveness
// window.addEventListener("deviceorientation", function (event) {
// engine.world.gravity.x = event.gamma / 30
// engine.world.gravity.y = event.beta / 30
// })
This Pen doesn't use any external CSS resources.