“Three.js+Cannon.js”的物理世界初探索

参考大佬: https://www.codercto.com/a/33760.html

1. 实现思路

实现思路

2. 关键代码及说明

  • three.js版本: 0.141.0
  • cannon版本: github:schteppe/cannon.js
    • 安装方式 npm install --save schteppe/cannon.js
// Step.1. 创建和设置物理世界

// 创建世界
const world = new Cannon.World();
// 向y轴负方向,创建重力加速度
world.gravity.set(0, -9.82, 0);
// 碰撞检测
world.broadphase = new Cannon.NaiveBroadphase();


// Step.2. 创建物理世界的物体

// 创建化球形
const sphereShape = new Cannon.Sphere(1);
// 创建化球体
const sphereBody = new Cannon.Body({
    
    
  mass: 5, // 质量
  position: new Cannon.Vec3(0, 20, 0),  // 位置
  shape: sphereShape // 形状
});
// 创建到物理世界
world.addBody(sphereBody);

// 创建化平面形状
const groundShape = new Cannon.Plane();
// 创建平面物体
const groundBody = new Cannon.Body({
    
    
  mass: 0,
  shape: groundShape,
});
// 平面初始是垂直于x0z轴的平面的,因此旋转90度
groundBody.quaternion.setFromAxisAngle(new Cannon.Vec3(1, 0, 0), -0.5 * Math.PI);
// 将平面物体添加到物理世界
world.addBody(groundBody);

// Step.3. 创建3D物体

// 创建球形几何体
const sphereGeometry = new Three.SphereGeometry(1, 32, 32);
// 创建材质
const sphereMaterial = new Three.MeshStandardMaterial({
    
    
  color: 0xff00ff
});
// 创建网格模型
const sphere = new Three.Mesh(sphereGeometry, sphereMaterial);
// 添加到场景
scene.add(sphere);

// 创建平面几何体
const groundGeometry = new Three.PlaneGeometry(100, 100, 32);
// 创建材质
const groundMaterial = new Three.MeshStandardMaterial({
    
    
  color: 0xffffff,
  side: Three.DoubleSide
});

// 创建平面几何体
const ground = new Three.Mesh(groundGeometry, groundMaterial);
// 同样的,平面初始是垂直于x0z轴的平面的,因此旋转90度
ground.rotation.x = -0.5 * Math.PI;
// 添加到场景
scene.add(ground);

// Step.4. 处理物理世界和3D世界的关联

// this.registerRenderFunc是追加一个requestAnimationFrame每帧执行的方法。第一个参数为方法名,更新方法内容使用;第二个参数为方法体。
this.registerRenderFunc('cannon-update', () => {
    
    
  // 降落时间的步长,60fps相当于每帧下降1/60,
  world.step(1 / 60);
  // 把物理世界物体的位置、角度的状态,同步更新到对应的3D物体上
  sphere.position.copy(sphereBody.position);
  sphere.quaternion.copy(sphereBody.quaternion);
});

3. 实现效果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/u010657801/article/details/129706358