Newer
Older
2024-Tsubasa / system / cannonjs_test / reference.html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>cannon-es reference</title>
</head>

<body>
    <script type="module">
        import * as CANNON from '../node_modules/cannon-es/dist/cannon-es.js'
        import * as THREE from '../node_modules/three/build/three.module.js'
        
        // Setup our physics world
        const world = new CANNON.World({
            gravity: new CANNON.Vec3(0, -9.82, 0), // m/s²
        })

        // Create a sphere body
        const radius = 1 // m
        const sphereBody = new CANNON.Body({
            mass: 5, // kg
            shape: new CANNON.Sphere(radius),
        })
        sphereBody.position.set(0, 10, 0) // m
        world.addBody(sphereBody)

        // Create a static plane for the ground
        const groundBody = new CANNON.Body({
            type: CANNON.Body.STATIC, // can also be achieved by setting the mass to 0
            shape: new CANNON.Plane(),
        })
        groundBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0) // make it face up
        world.addBody(groundBody)

        // Start the simulation loop
        function animate() {
            requestAnimationFrame(animate)

            world.fixedStep()

            // the sphere y position shows the sphere falling
            console.log(`Sphere y position: ${sphereBody.position.y}`)
        }
        animate()
    </script>
</body>

</html>