I have a problem with detecting collision between 2 models using BoundingSpheres in XNA 4.0. The code I'm using i very simple:
private bool IsCollision(Model model1, Matrix world1, Model model2, Matrix world2) { for (int meshIndex1 = 0; meshIndex1 < model1.Meshes.Count; meshIndex1++) { BoundingSphere sphere1 = model1.Meshes[meshIndex1].BoundingSphere; sphere1 = sphere1.Transform(world1); for (int meshIndex2 = 0; meshIndex2 < model2.Meshes.Count; meshIndex2++) { BoundingSphere sphere2 = model2.Meshes[meshIndex2].BoundingSphere; sphere2 = sphere2.Transform(world2); if (sphere1.Intersects(sphere2)) return true; } } return false; }
The problem I'm getting is that when I call this method from the Update method, the program behaves as if this method always returns true value (which of course is not correct). The code for calling is very simple (although this is only the test code):
if (IsCollision(model1, worldModel1, model2, worldModel2)) { Window.Title = "Intersects"; } What is causing this?
The way Im drawing the scene is to load the number of elements and their coordinates from a file like this (it is called from Update method):
OpenFileDialog Otvaranje = new OpenFileDialog(); if (ks.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.L)) { this.GraphicsDevice.Clear(Color.CornflowerBlue); Otvaranje.ShowDialog(); try { using (StreamReader sr = new StreamReader(Otvaranje.FileName)) { String linija; while ((linija = sr.ReadLine()) != null) { red = linija.Split(','); model = red[0]; x = red[1]; y = red[2]; z = red[3]; elementi.Add(Convert.ToInt32(model)); podatci.Add(new Vector3(Convert.ToSingle(x), Convert.ToSingle(y), Convert.ToSinglez))); sfere.Add(new BoundingSphere(new Vector3(Convert.ToSingle(x), Convert.ToSingle(y), Convert.ToSingle(z)), 1f)); } } And then in the Update() method I had the following code (this was my first attempt):
if(sfere.Count != 0){ for(int i = 1; i<sfere.Count; i++) { if(sfere[0].Intersects(sfere[i])) Window.Title = "Intersects"; } } This code never returned that collision is true because the bounding boxes are moving when the box moves, and I don't know why. The code that moves the box is this:
if (Microsoft.Xna.Framework.Input.ButtonState.Pressed == Mouse.GetState().LeftButton) { worldKutija = Matrix.CreateTranslation(new Vector3(0.01f, 0f, 0f)) * worldKutija; } So if the model is set to be the box it is drawn into the worldKutija, and all other models are drawn into world matrix so they would not move with the box model. So why are their BoundingSpheres moving? After this started happening I tried the code I posted in the original question, and got the problems I was talking about