cannon.js 物理引擎使用

我在开发大富翁游戏中,希望骰子能跟现实一样投掷,因为three.js中并没有物理引擎的引入,所以我需要引入cannon.js
cannon.js属于一个轻量级引擎,对cpu的性能要求比较低,非常适合放在web游戏中使用.
简单记录一下cannon.js使用过程中的要点,以便后面查阅.

大富翁源码地址:https://github.com/aoobao/backpacker

cannon.js 文档地址: https://schteppe.github.io/cannon.js

创建物理引擎世界

this.world = new CANNON.World()
this.world.gravity.set(0, 0, -9.8 * 70)    // 重力加速度设置 这里乘以70是因为之前创建的物体设置的比较大,所以需要加大重力加速度矫正

创建刚体

// 设置材质 这里设置了地面,墙壁,骰子三种材质
const cubeMaterial = new CANNON.Material('cube')
const material = new CANNON.Material('ground')
const wallMaterial = new CANNON.Material('wall')

// 地面
const bodyGround = new CANNON.Body({
      mass: 0,
      position: new CANNON.Vec3(0, 0, 0.1),
      shape: new CANNON.Plane(),
      material: material,
})

const wall1 = new CANNON.Body({
      mass: 0,
      position: new CANNON.Vec3(WIDTH / 2, 0, 0),
      shape: new CANNON.Plane(),
      material: wallMaterial,
})

wall1.quaternion.setFromAxisAngle(new CANNON.Vec3(0, 1, 0), -Math.PI / 2)

// 注意CANNON.Plane底部是包含材质的,并不是只有一个平面,假设 position: new CANNON.Vec3(0, 0, 0), 那么z方向<0的都是存在材质,物体如果在z方向<0 会被挤到上来,在z+方向有一个力
// 设置两个材质之间的参数值,因为我不希望骰子斜靠在墙上,所以墙壁和骰子的摩擦力设置成了0.
const groundContactMaterial = new CANNON.ContactMaterial(material, cubeMaterial, {
      friction: 0.1,    // 摩擦力
      restitution: 0.5, // 弹性
})

const wallContactMaterial = new CANNON.ContactMaterial(wallMaterial, cubeMaterial, {
      friction: 0,
      restitution: 1,
})

创建骰子,并给予初速度及角速度

addBox(cube: Cube, speed = 1) {
    return new Promise<void>((resolve, reject) => {
      const pos = cube.instance.position
      const qua = cube.instance.quaternion
      const size = cube.size
      const halfExtents = new CANNON.Vec3(size / 2, size / 2, size / 2)
      const bodyBox = new CANNON.Body({
        mass: 5,
        position: new CANNON.Vec3(pos.x, pos.y, pos.z),
        shape: new CANNON.Box(halfExtents),
        quaternion: new CANNON.Quaternion(qua.x, qua.y, qua.z, qua.w),
        linearDamping: 0.01,
        angularDamping: 0.05,
        material: cubeMaterial,
      })

      const x = 500 * speed * randPM()
      const y = 500 * speed * randPM()
      const z = 300 + 300 * speed

      bodyBox.velocity.set(x, y, z)
      bodyBox.angularVelocity.set(rendAngular(), rendAngular(), (50 + 50 * Math.random()) * randPM())

      function rendAngular() {
        return (10 + 10 * Math.random()) * randPM()
      }

      const box: PhysicsBody = {
        type: 'cube',
        cube,
        bodyBox,
        resolve,
        reject,
        timer: new Date().getTime(),
      }

      this.world.addBody(bodyBox)
      this.bodyList.push(box)
    })
  }

每帧渲染的时候更新计算

// updatePhysics
  render(res: any) {
    const delta = res.delta as number
    if (delta) {
      // console.log(delta)
      this.world.step(fixedTimeStep, delta, maxSubSteps)
      for (let i = this.bodyList.length - 1; i >= 0; i--) {
        const box = this.bodyList[i]
        // 将物理引擎中的计算值同步到threejs中的对象中(position,quaternion),并判断CANNON.Body的速度和角速度是否低于某个阈值,
        // 如果低于阈值后,则可以认为骰子已经停止运动了,可以读取骰子的朝向及点数值了.
        if (this.syncInstanceValue(box)) {
          this.bodyList.splice(i, 1)

          // 延迟去除,多个骰子
          setTimeout(() => {
            this.world.remove(box.bodyBox)
          }, 5000)
          box.resolve()
        }
      }
    }
  }

以上记录了比较关键的内容,源码可以参考https://github.com/aoobao/backpacker/blob/master/src/assets/physics.ts

标签: none

添加新评论