使用 Three.js 和 Cannon.js 构建真实 3D 骰子动画
3D 场景搭建
Cannon.js
-
设置重力。
this.world.gravity.set(0, 0, -9.8 * 16);
-
设置
骰子
、地面
以及墙体
三种材质,并两两设置联系材质。this.diceBodyMaterial = new CANNON.Material(); const deskBodyMaterial = new CANNON.Material(); const barrierBodyMaterial = new CANNON.Material(); this.world.addContactMaterial(new CANNON.ContactMaterial(deskBodyMaterial, this.diceBodyMaterial, { friction: 0.01, restitution: 0.5, })); this.world.addContactMaterial(new CANNON.ContactMaterial(barrierBodyMaterial, this.diceBodyMaterial, { friction: 0, restitution: 0.5, })); this.world.addContactMaterial(new CANNON.ContactMaterial(this.diceBodyMaterial, this.diceBodyMaterial, { friction: 0, restitution: 0.5, }));
-
添加地面以及墙体模型
this.world.addBody(new CANNON.Body({ mass: 0, shape: new CANNON.Plane(), material: deskBodyMaterial, })); let barrier = new CANNON.Body({ mass: 0, shape: new CANNON.Plane(), material: barrierBodyMaterial, }) barrier.position.set(0, this.dimentions