Created
May 15, 2023 14:11
-
-
Save crispy-computing-machine/7903febb866a0503a3f492a4f1f9098b to your computer and use it in GitHub Desktop.
Bouncy Ball JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<style> | |
#myCanvas { | |
border: 1px solid black; | |
} | |
</style> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.14.2/matter.min.js"></script> | |
</head> | |
<body> | |
<canvas id="myCanvas" width="800" height="600"></canvas> | |
<script> | |
// fetch canvas | |
var canvas = document.getElementById('myCanvas'); | |
// setup Matter.js | |
var Engine = Matter.Engine, | |
Render = Matter.Render, | |
World = Matter.World, | |
Bodies = Matter.Bodies, | |
Mouse = Matter.Mouse, | |
MouseConstraint = Matter.MouseConstraint; | |
var engine = Engine.create(); | |
// create a renderer | |
var render = Render.create({ | |
element: document.body, | |
canvas: canvas, | |
engine: engine, | |
options: { | |
wireframes: false // required to apply colors | |
} | |
}); | |
// create a ball | |
var ball = Bodies.circle(400, 200, 50, { | |
restitution: 1.3, // This makes the object bouncy | |
render: { | |
fillStyle: 'red' | |
} | |
}); | |
// create ground | |
var ground = Bodies.rectangle(400, 610, 810, 60, { isStatic: true }); | |
// add all of the bodies to the world | |
World.add(engine.world, [ball, ground]); | |
// add mouse control | |
var mouse = Mouse.create(render.canvas), | |
mouseConstraint = MouseConstraint.create(engine, { | |
mouse: mouse, | |
constraint: { | |
stiffness: 0.1, | |
render: { | |
visible: false | |
} | |
} | |
}); | |
World.add(engine.world, mouseConstraint); | |
render.mouse = mouse; | |
// keep the mouse in sync with rendering | |
render.mouse = mouse; | |
// run the engine | |
Engine.run(engine); | |
// run the renderer | |
Render.run(render); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment