Rigid body (shape) in bullet/ammo.js from a mesh in three.js

寵の児 提交于 2019-12-08 05:10:30

It looks like you can do some work to turn an arbitrary Three.js mesh into a Bullet concave mesh. This is supported by Physi.js, which is a plug and play solution to link Three.js directly to ammo.js. I personally wouldn't recommend using the project (Physi.js) but you can look at the source code to see how they implement concave meshes.

First they loop over the geometry to create a custom list of "triangle" data objects on these lines of physi.js

for ( i = 0; i < geometry.faces.length; i++ ) {
    face = geometry.faces[i];
    if ( face instanceof THREE.Face3) {
        triangles.push([
            ...

Then these triangles are passed off to Ammo.js to make a new Ammo.btBvhTriangleMeshShape on these lines:

for ( i = 0; i < description.triangles.length; i++ ) {
    ...
    triangle_mesh.addTriangle( _vec3_1, _vec3_2, _vec3_3, true );
}

...

shape = new Ammo.btBvhTriangleMeshShape( triangle_mesh, true, true );

This should be a good starting point for building your own Ammo.js custom mesh.

There are lots of threads around the web, that Physijs Concave mesh does not work with collission. It seems, that btBvhTriangleMeshShape is not intended to work with collission in ammo.js, as I found out searching for that topic in bullet related forums.

What worked for me, is btConvexHullShape:

var triangle, triangle_mesh = new Ammo.btTriangleMesh;
var btConvexHullShape = new Ammo.btConvexHullShape();
var _vec3_1 = new Ammo.btVector3(0,0,0);
var _vec3_2 = new Ammo.btVector3(0,0,0);
var _vec3_3 = new Ammo.btVector3(0,0,0);
for ( i = 0; i < triangles.length; i++ ) {
    triangle = triangles[i];
    _vec3_1.setX(triangle[0].x);
    _vec3_1.setY(triangle[0].y);
    _vec3_1.setZ(triangle[0].z);
    btConvexHullShape.addPoint(_vec3_1,true);
    _vec3_2.setX(triangle[1].x);
    _vec3_2.setY(triangle[1].y);
    _vec3_2.setZ(triangle[1].z);
    btConvexHullShape.addPoint(_vec3_2,true);
    _vec3_3.setX(triangle[2].x);
    _vec3_3.setY(triangle[2].y);
    _vec3_3.setZ(triangle[2].z);
    btConvexHullShape.addPoint(_vec3_3,true);
    triangle_mesh.addTriangle(
        _vec3_1,
        _vec3_2,
        _vec3_3,
        true
    );
}
return btConvexHullShape;

In the process of learning physic based 3d with threejs, I also want to mention the following best practice: when using complex models, create a low poly model that you can push to that converter function instead of the original model, or you will encounter a stack overflow.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!