I’d like to make collisions in my XNA project and I tried using BoundingBoxes. I wanted to have collisiond with house’s walls so I used this code to make BoundingBox for each mesh in model:
public void CreateBB()
{
Model model = Game1.ModelRes[nazwaModelu];
Matrix worldTransform = world;
foreach (ModelMesh mesh in model.Meshes)
{
Vector3 min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
Vector3 max = new Vector3(float.MinValue, float.MinValue, float.MinValue);
foreach (ModelMeshPart meshPart in mesh.MeshParts)
{
int vertexStride = meshPart.VertexBuffer.VertexDeclaration.VertexStride;
int vertexBufferSize = meshPart.NumVertices * vertexStride;
float[] vertexData = new float[vertexBufferSize / sizeof(float)];
meshPart.VertexBuffer.GetData<float>(vertexData);
for (int i = 0; i < vertexBufferSize / sizeof(float); i += vertexStride / sizeof(float))
{
Vector3 transformedPosition = Vector3.Transform(new Vector3(vertexData[i], vertexData[i + 1], vertexData[i + 2]), worldTransform);
min = Vector3.Min(min, transformedPosition);
max = Vector3.Max(max, transformedPosition);
}
}
Game1.boxory.Add(new BoundingBox(min, max));
}
}
I received 6 equal BoundingBoxes. Each BoundingBox was the same and thus collisions work only with one wall. Is it problem of this code?(or maybe with exporting models with many meshes)?
All ModelMeshParts reference the same vertexBuffer which contains the data for the whole model, not just that ModelMeshPart. Each ModelMeshPart simply has its own start index in that buffer and the number of verts it uses. So each time you called
GetData(), you populated your float array from the VB’s start (the zeroth element/index) instead of the ModelMeshPart’s start index.