好的,我肯定忽略了一些非常明显的问题,但问题是:
在我的项目中,我使用了两种类型的碰撞:球体到球体和盒子到盒子。两者都遇到同样的问题;他们总是检测到两个对象之间的碰撞。
在我的 baseGameObject 类中,我声明了边界框:
BoundingBox bb;
我还有为模型创建边界框并使用它来定义 bb 的方法:
public void Initialize()
{
bb = CreateBoundingBox();
}
protected BoundingBox CalculateBoundingBox()
{
Vector3 modelMax = new Vector3(float.MinValue, float.MinValue, float.MinValue);
Vector3 modelMin = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
transforms = new Matrix[model.Bones.Count];
foreach (ModelMesh mesh in model.Meshes)
{
Vector3 meshMax = new Vector3(float.MinValue, float.MinValue, float.MinValue);
Vector3 meshMin = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
foreach (ModelMeshPart part in mesh.MeshParts)
{
int stride = part.VertexBuffer.VertexDeclaration.VertexStride;
byte[] vertexData = new byte[stride * part.NumVertices];
part.VertexBuffer.GetData(part.VertexOffset * stride, vertexData, 0, part.NumVertices, 1); // fixed 13/4/11
Vector3 vertPosition = new Vector3();
for (int ndx = 0; ndx < vertexData.Length; ndx += stride)
{
vertPosition.X = BitConverter.ToSingle(vertexData, ndx);
vertPosition.Y = BitConverter.ToSingle(vertexData, ndx + sizeof(float));
vertPosition.Z = BitConverter.ToSingle(vertexData, ndx + sizeof(float) * 2);
meshMin = Vector3.Min(meshMin, vertPosition);
meshMax = Vector3.Max(meshMax, vertPosition);
}
}
meshMin = Vector3.Transform(meshMin, transforms[mesh.ParentBone.Index]);
meshMax = Vector3.Transform(meshMax, transforms[mesh.ParentBone.Index]);
modelMin = Vector3.Min(modelMin, meshMin);
modelMax = Vector3.Max(modelMax, meshMax);
}
return new BoundingBox(modelMin, modelMax);
}
然后我制作了一种方法来使用 bb 进行碰撞。
public bool BoxCollision(BoundingBox secondBox)
{
if (bb.Intersects(secondBox))
return true;
else
return false;
}
最后我使用该方法来确定碰撞检测。
public void CollisionCheck()
{
foreach (NonPlayerChar npc in npcList)
{
if(player.SphereCollision(npc.model, npc.getWorldRotation()))
{ npc.position = vector3.Zero; }
if (player.BoxCollision(npc.bb))
{ npc.position = vector3.Zero; }
}
}
位置的东西是一个测试,看看它们是否会发生碰撞。我可以将对象位置设置为任何位置,并且仍然可以检测到碰撞。我对边界球碰撞有同样的问题。
public bool SphereCollision(Model secondModel, Matrix secondWorld)
{
foreach (ModelMesh modelMeshes in model.Meshes)
{
foreach (ModelMesh secondModelMesh in secondModel.Meshes)
{
if(modelMeshes.BoundingSphere.Transform(getWorldRotation()).Intersects(secondModelMesh.BoundingSphere.Transform(secondWorld)))
return true;
}
}
return false;
}
有谁知道我做错了什么?