- 安装
cnpm install cannon --save
- 导入
import * as CANNON from "cannon";
- 用Three.js搭建物理场景(这里用的ThingOrigin.js,可以直接用three.js写)
let mainScene = ThingOrigin.addScene("ttt", document.getElementById("d1"));
let modelB = ThingOrigin.model.initSphere("wb");
modelB.position.set(0, 20, 0);
mainScene.add(modelB);
- 用Cannon.js 搭建物理世界
world = new CANNON.World();
world.gravity.set(0, -10, 0); //设置重力
world.broadphase = new CANNON.NaiveBroadphase(); //碰撞必要
world.solver.iterations = 10; //迭代次数
//创建地面
var groundShape = new CANNON.Plane();
var groundBody = new CANNON.Body({ mass: 0 });
groundBody.addShape(groundShape);
groundBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2);
world.addBody(groundBody);
//创建球体
shape = new CANNON.Sphere(10);
mass = 1;
body = new CANNON.Body({mass: 1});
body.addShape(shape);
body.position.set(0, 30, 0);
body.angularVelocity.set(2, 5, 2); //角速度
body.angularDamping = 0.6; //角度阻尼
world.addBody(body);
- 让Three.js中物体复制Cannon.js世界的位置与旋转
function animate() {
requestAnimationFrame(animate);
modelB.position.copy(body.position);
modelB.quaternion.copy(body.quaternion);
}