//This method is performing basic collision detection between two models //Whole model is surrounded by BoundingBox stored in model.Tag info public static bool GeneralDecorationCollisionCheck(GameObject unit, GameObject decoration) { //Retrieving data about BoundingBox from model.Tag for first model ModelExtra animationData1 = unit.currentModel.Model.Tag as ModelExtra; BoundingSphere originalBox1 = animationData1.boundingSphere; BoundingSphere Box1 = XNAUtils.TransformBoundingSphere(originalBox1, unit.GetWorldMatrix()); //Doing the same thing for second model ModelExtra animationData2 = decoration.currentModel.Model.Tag as ModelExtra; BoundingBox originalBox2 = animationData2.boundingBox; BoundingBox Box2 = XNAUtils.TransformBoundingBox(originalBox2, decoration.GetWorldMatrix()); Building deco = (Building)decoration; deco.boundingBox = Box2; //Checking if global bounding Box(surronds whole model) intersects another Box bool collision = Box1.Intersects(Box2); return collision; }
//This method performs much more detailed collision check. //It checks if there is collision for each mesh of model public static bool DetailedDecorationCollisionCheck(GameObject unit, GameObject deco) { Building decoration = (Building)deco; //first we check if there is general collision between two models //If method returns false we dont have to perform detailed check if (!GeneralDecorationCollisionCheck(unit, decoration)) return false; //Here we are creating BoundingBox for each mesh for model1 Matrix[] model1Transforms = new Matrix[unit.currentModel.Model.Bones.Count]; unit.currentModel.Model.CopyAbsoluteBoneTransformsTo(model1Transforms); BoundingSphere[] model1Boxs = new BoundingSphere[unit.currentModel.Model.Meshes.Count]; for (int i = 0; i < unit.currentModel.Model.Meshes.Count; i++) { ModelMesh mesh = unit.currentModel.Model.Meshes[i]; BoundingSphere origSphere = mesh.BoundingSphere; Matrix trans = model1Transforms[mesh.ParentBone.Index] * unit.GetWorldMatrix(); BoundingSphere transBox = XNAUtils.TransformBoundingSphere(origSphere, trans); model1Boxs[i] = transBox; } bool collision = false; //Check if any of created before Boxs intersects with another Box for (int i = 0; i < model1Boxs.Length; i++) for (int j = 0; j < decoration.meshBoundingBoxes.Count; j++) if (model1Boxs[i].Intersects(decoration.meshBoundingBoxes[j])) return true; return collision; }