我正在用c#开发一个游戏引擎,我正在使用BulletSharp进行物理攻击。除了立方体之外,它运行良好:
http://i.stack.imgur.com/EPfrw.png
(轴对齐边界框为透明红色,模型为白色)
休息时,他们边缘的立场。因为我是从Collada模型加载的,所以我创建了一个ConvexHullShape()
并将数据添加为矢量云。虽然使用BoxShape()
会更有效(并且正常工作),但我不能保证所有模型都是立方体。我无法弄清楚为什么它们停留在顶点而不是平坦的边缘上。我的ConvexHullShape
实现是错误的还是我需要使用不同类型的形状(物理才能正常工作)?
public RigidBody AddDynamicGeometry(ColladaGeometry geometry, Matrix4 transform)
{
List<Vector3> points = new List<Vector3>();
foreach (Triangle tri in geometry.triangles)
{
points.Add(tri.vertices[0]);
points.Add(tri.vertices[1]);
points.Add(tri.vertices[2]);
}
CollisionShape shape = new ConvexHullShape(points);
shape.UserObject = geometry;
collisionShapes.Add(shape);
RigidBody body = CreateRigidBody(geometry.triangles.Count * 10, transform, shape);
return body;
}
public RigidBody CreateRigidBody(float mass, Matrix4 startTransform, CollisionShape shape)
{
bool isDynamic = (mass != 0.0f);
Vector3 localInertia = Vector3.Zero;
if (isDynamic)
shape.CalculateLocalInertia(mass, out localInertia);
DefaultMotionState myMotionState = new DefaultMotionState(startTransform);
RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, shape, localInertia);
RigidBody body = new RigidBody(rbInfo);
physics_world.AddRigidBody(body);
return body;
}
答案 0 :(得分:1)
ConvexHullShape期望质心(COM)为(0,0,0),但立方体偏离中心,使其朝向角落倾斜。
您可以使用ConvexTriangleMeshShape.CalculatePrincipalAxisTransform找到正确的COM。然后你可以从每个顶点减去COM以使COM回到0.但是,创建一个具有多维数据集的本地中心的CompoundShape会更容易。
// Create a ConvexTriangleMeshShape from the points
const int indexStride = 3 * sizeof(int);
const int vertexStride = 12;
int vertexCount = points.Count;
int indexCount = vertexCount / 3;
TriangleIndexVertexArray vertexArray = new TriangleIndexVertexArray();
IndexedMesh mesh = new IndexedMesh();
mesh.Allocate(vertexCount, vertexStride, indexCount, indexStride);
Vector3Array vdata = mesh.Vertices;
IntArray idata = mesh.TriangleIndices;
for (int i = 0; i < vertexCount; i++)
{
vdata[i] = points[i];
idata[i] = i;
}
vertexArray.AddIndexedMesh(mesh);
ConvexTriangleMeshShape shape = new ConvexTriangleMeshShape(vertexArray, true);
// Calculate center of mass
Matrix center = Matrix.Identity;
Vector3 inertia;
float volume;
shape.CalculatePrincipalAxisTransform(ref center, out inertia, out volume);
// Create a CompoundShape with COM offset
CompoundShape compound = new CompoundShape();
compound.AddChildShape(Matrix.Invert(center), shape);
注意:ConvexTriangleMeshShape.CalculatePrincipalAxisTransform适用于SVN中继,但不适用于BulletSharp 2.82。很快就会发布bug修复。