我如何使用 Ammo.btCompoundShapeBullet Physics 的 JavaScript 端口? 解决方案:另一条评论:

如何解决我如何使用 Ammo.btCompoundShapeBullet Physics 的 JavaScript 端口? 解决方案:另一条评论:

我使用的是 Ammo.js,它是 C++ Bullet Physics 的直接 JavaScript 端口。不幸的结果是文档是 C++,如果您的语言是 Python 和 JavaScript,则不适合阅读。

我有 documentation for Ammo.btCompoundShape here 但无法理解。

我在这里有一个工作代码,其中 Bone 实例刚好从地板上掉下来,你会看到。不用担心“骨头”的命名,在这个开发阶段只是为了测试两个块的复合形状。

class RenderEngine {
  constructor(gameEngine) {
    this.gameEngine = gameEngine
    this.gameEngine.clock = new THREE.Clock();
    this.scene = new THREE.Scene();
    this.scene.background = new THREE.Color(0xbfd1e5);
    this.camera = new THREE.PerspectiveCamera(60,window.innerWidth / window.innerHeight,0.2,5000);
    this.camera.position.set(0,30,70);
    this.camera.lookAt(new THREE.Vector3(0,0));
    const hemiLight = new THREE.HemisphereLight(0xffffff,0xffffff,0.1);
    hemiLight.color.setHSL(0.6,0.6,0.6);
    hemiLight.groundColor.setHSL(0.1,1,0.4);
    hemiLight.position.set(0,50,0);
    this.scene.add(hemiLight);
    const dirLight = new THREE.DirectionalLight(0xffffff,1);
    dirLight.color.setHSL(0.1,0.95);
    dirLight.position.set(-1,1.75,1);
    dirLight.position.multiplyScalar(100);
    this.scene.add(dirLight);
    dirLight.castShadow = true;
    dirLight.shadow.mapSize.width = 2048;
    dirLight.shadow.mapSize.height = 2048;
    const d = 50;
    dirLight.shadow.camera.left = -d;
    dirLight.shadow.camera.right = d;
    dirLight.shadow.camera.top = d;
    dirLight.shadow.camera.bottom = -d;
    dirLight.shadow.camera.far = 13500;
    this.renderer = new THREE.WebGLRenderer({
      antialias: true
    });
    this.renderer.setClearColor(0xbfd1e5);
    this.renderer.setPixelRatio(window.devicePixelRatio);
    this.renderer.setSize(window.innerWidth,window.innerHeight);
    document.body.appendChild(this.renderer.domElement);
    this.renderer.shadowMap.enabled = true;
  }
  renderFrame() {
    this.renderer.render(this.scene,this.camera)
  }
}

class PhysicsEngine {
  constructor(gameEngine,physicsEngine) {
    this.gameEngine = gameEngine
    let collisionConfiguration = new Ammo.btDefaultCollisionConfiguration(),dispatcher = new Ammo.btCollisionDispatcher(collisionConfiguration),overlappingPairCache = new Ammo.btDbvtBroadphase(),solver = new Ammo.btSequentialImpulseConstraintSolver();
    this.tmpTrans = new Ammo.btTransform();
    this.physicsWorld = new Ammo.btDiscreteDynamicsWorld(dispatcher,overlappingPairCache,solver,collisionConfiguration);
    this.physicsWorld.setGravity(new Ammo.btVector3(0,-10,0));
  }
  updateFrame() {
    this.physicsWorld.stepSimulation(this.gameEngine.clock.getDelta(),10);
    this.gameEngine.objects.forEach(object => {
      const ms = object.ammo.getMotionState()
      if (ms) {
        ms.getWorldTransform(this.tmpTrans)
        const p = this.tmpTrans.getOrigin()
        const q = this.tmpTrans.getRotation()
        object.mesh.position.set(p.x(),p.y(),p.z())
        object.mesh.quaternion.set(q.x(),q.y(),q.z(),q.w())
      }
    })
  }
}

class GameEngine {
  constructor(renderEngine,physicsEngine) {
    this.objects = []
    this.renderEngine = new RenderEngine(this,renderEngine)
    this.physicsEngine = new PhysicsEngine(this,physicsEngine)
  }
  run() {
    this.physicsEngine.updateFrame()
    this.renderEngine.renderFrame()
    requestAnimationFrame(() => {
      this.run()
    });
  }
  add(object) {
    this.objects.push(object)
    return this.objects.length - 1
  }
  remove(objectIndex) {
    this.objects[objectIndex] = false
  }
}

class Box {
  constructor(gameEngine,properties) {
    this.gameEngine = gameEngine
    this._initPhysics_(properties)
    this._initRendering_(properties)
    this.id = gameEngine.add(this)
  }
  _initPhysics_(properties) {
    const pos = properties.pos
    const quat = properties.quat
    const scale = properties.scale
    const mass = properties.mass
    const group = properties.group
    const interactionGroup = properties.interactionGroup
    const physicsWorld = this.gameEngine.physicsEngine.physicsWorld
    const transform = new Ammo.btTransform()
    transform.setIdentity()
    transform.setOrigin(new Ammo.btVector3(pos.x,pos.y,pos.z))
    transform.setRotation(new Ammo.btQuaternion(quat.x,quat.y,quat.z,quat.w))
    const motionState = new Ammo.btDefaultMotionState(transform)
    const colShape = new Ammo.btBoxShape(new Ammo.btVector3(scale.x * 0.5,scale.y * 0.5,scale.z * 0.5))
    colShape.setMargin(0.05)
    const localInertia = new Ammo.btVector3(0,0)
    colShape.calculateLocalInertia(mass,localInertia)
    const rbInfo = new Ammo.btRigidBodyConstructionInfo(mass,motionState,colShape,localInertia)
    const body = new Ammo.btRigidBody(rbInfo)
    physicsWorld.addRigidBody(body,group,interactionGroup)
    this.ammo = body
  }
  _initRendering_(properties) {
    const pos = properties.pos
    const scale = properties.scale
    const color = properties.color
    this.mesh = new THREE.Mesh(new THREE.BoxBufferGeometry(),new THREE.MeshPhongMaterial({
      color
    }))
    this.mesh.position.set(pos.x,pos.z)
    this.mesh.scale.set(scale.x,scale.y,scale.z)
    this.mesh.castShadow = true
    this.mesh.receiveShadow = true
    this.gameEngine.renderEngine.scene.add(this.mesh)
  }
}


class Bone {
  constructor(gameEngine,properties) {
    this.gameEngine = gameEngine
    this._initPhysics_(properties)
    this._initRendering_(properties)
    this.id = gameEngine.add(this)
  }
  _initPhysics_(properties) {
    const pos = properties.pos
    const quat = properties.quat
    const scale = properties.scale
    const mass = properties.mass
    const group = properties.group
    const interactionGroup = properties.interactionGroup
    const physicsWorld = this.gameEngine.physicsEngine.physicsWorld
    const compoundShape = new Ammo.btCompoundShape()
    this._addSection_(compoundShape,{
      pos,quat,scale,offset: {
        x: 0,y: 0,z: 0
      },rotation: {
        x: 0,z: 0,w: 0
      }
    })
    this._addSection_(compoundShape,w: 0
      }
    })
    const transform = new Ammo.btTransform()
    transform.setIdentity()
    transform.setOrigin(new Ammo.btVector3(pos.x,quat.w))
    const motionState = new Ammo.btDefaultMotionState(transform)
    compoundShape.setMargin(0.05)
    const localInertia = new Ammo.btVector3(0,0)
    compoundShape.calculateLocalInertia(mass,compoundShape,scale.z)
    this.mesh.castShadow = true
    this.mesh.receiveShadow = true
    this.gameEngine.renderEngine.scene.add(this.mesh)
  }
  _addSection_(compoundShape,properties) {
    const pos = properties.pos
    const quat = properties.quat
    const scale = properties.scale
    const offset = properties.offset
    const rotation = properties.rotation
    const transform = new Ammo.btTransform()
    transform.setIdentity()
    transform.setOrigin(new Ammo.btVector3(pos.x + offset.x,pos.y + offset.y,pos.z + offset.z))
    transform.setRotation(new Ammo.btQuaternion(quat.x + rotation.x,quat.y + rotation.y,quat.z + rotation.z,quat.w + rotation.w))
    const motionState = new Ammo.btDefaultMotionState(transform)
    const colShape = new Ammo.btBoxShape(new Ammo.btVector3(scale.x * 0.5,scale.z * 0.5))
    compoundShape.addChildShape(transform,colShape)
  }
}

Ammo().then((Ammo) => {
  const gameEngine = new GameEngine(THREE,Ammo)
  const plane = new Box(gameEngine,{
    pos: {
      x: 0,z: 0
    },quat: {
      x: 0,w: 1
    },scale: {
      x: 50,y: 2,z: 50
    },mass: 0,group: 1,interactionGroup: 1,color: 0xa0afa4
  })
  const box1 = new Box(gameEngine,y: 5,scale: {
      x: 2,z: 2
    },mass: 1,color: 0xa0afa4
  })
  const box2 = new Box(gameEngine,{
    pos: {
      x: 0.75,y: 8,z: 0.75
    },color: 0xa0afa4
  })
  const bone1 = new Bone(gameEngine,{
    pos: {
      x: -0.75,y: 10,z: -0.75
    },color: 0xa0afa4
  })
  console.log("gameEngine",gameEngine)
  gameEngine.run()
})
canvas,body,html {
  margin: 0px;
  padding: 0px;
  overflow: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r124/three.min.js"></script>
<script src="https://cdn.babylonjs.com/ammo.js"></script>

两个 Box 实例落在地板上 (plane),bone1 落下。我想我在 Ammo.btCompoundShape 上做错了什么。没有错误。正确的做法是什么?

解决方法

bone 实际上并没有完全落下,而是停在了飞机的中间。

原因:您正在转换两次:

  1. motionState 已转换
  2. compoundShape_addSection_
  3. 内再次转换

这样 compoundShape 确实发生碰撞并且不会落下,但是可见的 colShape 被偏移(从 compoundShape 的参考位置)到 plane 内部.

您可以看到,如果您尝试更改 _addSection_ 中的这一行:

transform.setOrigin(new Ammo.btVector3(0,2.0))

解决方案:

不要变换两次。例如。仅变换 motionState,而不变换 compoundShape
例如。删除这两行:

_addSection_(compoundShape,properties) {
    const transform = new Ammo.btTransform()
    transform.setIdentity()
    // -- disable second transform: --
    // transform.setOrigin(new Ammo.btVector3( ... ))
    // transform.setRotation(new Ammo.btQuaternion( ... ))

    const colShape = new Ammo.btBoxShape(new Ammo.btVector3(scale.x * 0.5,scale.y * 0.5,scale.z * 0.5))
    compoundShape.addChildShape(transform,colShape)
}

另一条评论:

localInertia 也应用于两次:

  • compoundShape.calculateLocalInertia(mass,localInertia)
  • const rbInfo = new Ammo.btRigidBodyConstructionInfo(mass,motionState,compoundShape,localInertia)

这显然有效,但可能不是故意的。它不会失败,因为它是 0,0。如果您确实想要两个惯性,我也认为您不能为它们使用相同的 localInertia 对象,但您应该创建第二个对象,例如localInertiaCompoundShape,但我不确定。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-