<!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> <style> body { margin: 0; overflow: hidden; } canvas { display: block; } </style> </head> <body> <div id="canvas"></div> <!-- インポートマップというやつらしい、よくわからない --> <script type="importmap"> { "imports": { "three": "../node_modules/three/build/three.module.js", "three/examples/jsm/controls/OrbitControls": "../node_modules/three/examples/jsm/controls/OrbitControls.js", "cannon-es": "../node_modules/cannon-es/dist/cannon-es.js", "cannon-es-debugger": "../node_modules/cannon-es-debugger/dist/cannon-es-debugger.js" } } </script> <script type="module"> import * as CANNON from 'cannon-es' import * as THREE from 'three' import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls' import CannonDebugger from 'cannon-es-debugger' // 世界の作成と重力の設定 const world = new CANNON.World({ gravity: new CANNON.Vec3(0, -9.82, 0), }); // シーン・カメラ・コントローラー・補助線・レンダラーの作成 const scene = new THREE.Scene(); // シーン const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 1000); // カメラ (fov(視点を移動させなくても見える範囲, アスペクト、近距離、遠距離)) camera.position.set(0, 10, 40); // カメラの位置設定 const axesHelper = new THREE.AxesHelper(30); // 補助線(x, y, z) scene.add(axesHelper); // シーンに追加 const renderer = new THREE.WebGLRenderer({ // レンダラー antialias: true, alpha: true }); renderer.setSize(window.innerWidth, window.innerHeight); renderer.physicallyCorrectLights = true; const controls = new OrbitControls(camera, renderer.domElement); // コントローラー document.getElementById("canvas").appendChild(renderer.domElement); // レンダラーをcanvas(画面)につなげる // cannon debugger const cannonDebugger = new CannonDebugger(scene, world); // 地面の作成 const groundBody = new CANNON.Body({ mass: 0, //mass : 重量 0に設定することで静的(止まる) shape: new CANNON.Box( // shape : 形と大きさの決定 new CANNON.Vec3(10, 0.01, 10) ), material: new CANNON.Material({ // restitution: 0.5, // restituion : 反発係数 }), }); groundBody.quaternion.setFromEuler(0, 0, -Math.PI / 9); world.addBody(groundBody); // worldに加える // 球体の作成 const radius = 2.5; const sphereBody = new CANNON.Body({ mass: 5, //kg shape: new CANNON.Sphere(radius), position: new CANNON.Vec3(0, 10, 0), material: new CANNON.Material({ restitution: 1, }), }); world.addBody(sphereBody); // 画面の大きさが変更されたときに動的に修正 function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); } window.addEventListener('resize', onWindowResize); // アニメーションの作成 function animate() { world.fixedStep(); // fps60 (1/60 ms) controls.update(); // カメラコントローラーの更新 cannonDebugger.update(); renderer.render(scene, camera); requestAnimationFrame(animate); }; animate(); </script> </body> </html>