cannon-es-control
Version:
A lightweight 3D physics engine written in JavaScript with control system tools
61 lines (50 loc) • 1.8 kB
HTML
<html lang="en">
<head>
<meta charset="utf-8" />
<title>cannon.js - spring demo</title>
<link rel="stylesheet" href="css/style.css" type="text/css" />
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0" />
</head>
<body>
<script type="module">
import * as CANNON from '../dist/cannon-es-control.js'
import { Demo } from './js/Demo.js'
const demo = new Demo()
demo.addScene('Flat box', () => {
const world = setupWorld(demo)
const size = 1
// Create a static sphere
const sphereShape = new CANNON.Sphere(0.1)
const sphereBody = new CANNON.Body({ mass: 0 })
sphereBody.addShape(sphereShape)
world.addBody(sphereBody)
demo.addVisual(sphereBody)
// Create a box body
const boxShape = new CANNON.Box(new CANNON.Vec3(size, size, size * 0.3))
const boxBody = new CANNON.Body({ mass: 5 })
boxBody.addShape(boxShape)
boxBody.position.set(size, -size, 0)
world.addBody(boxBody)
demo.addVisual(boxBody)
const spring = new CANNON.Spring(boxBody, sphereBody, {
localAnchorA: new CANNON.Vec3(-size, size, 0),
localAnchorB: new CANNON.Vec3(0, 0, 0),
restLength: 0,
stiffness: 50,
damping: 1,
})
// Compute the force after each step
world.addEventListener('postStep', (event) => {
spring.applyForce()
})
})
demo.start()
function setupWorld(demo) {
const world = demo.getWorld()
world.gravity.set(0, -10, 0)
return world
}
</script>
</body>
</html>