I have been having a problem doing 3D collision detection in a game I have been trying to make for several weeks now. What I am trying to do is prevent a PlayerModel object from colliding with Obstacle(cube) objects. The code I have right now works perfectly fine but it only works correctly with the first Obstacle in the list of Obstacle objects I have. I have tried using a foreach and for statement to try and go through each object in the list but neither method worked. Also putting breaks and continue statements did not work either. The first code block that I want to post is the code in the player model object that checks for the collision.
I decided to leave in the comments I had from when I was debugging the code. Also this code block is all happening in the PlayerModel class.
//update future bounding sphere based on input
this.futureBoundingSphere = new BoundingSphere(this.futurePosition.Translation, 10.5f);
//collision checking last
//What i think is going on - At first only one cube was being checked, so i just break out of the statement if we hit soemthing.,
//i think that was the only way i could get the collision to get checked on multiple objects.
//Also, i must take note of the bounding spehers, It is likely that the spacemans collision sphere is being drawn waaaay to large, suggest scaling spacemodel to test
foreach (BasicModel obstacleModel in game.obstacles.models)
{
if (this.wholeCollidesWith(futureBoundingSphere, obstacleModel, obstacleModel.GetWorld()))
{
//note - First object in the list does second statement, last object does first statement
game.aColor = Color.AliceBlue;
futurePosition.Translation = this.world.Translation;
//break; ////- adding in break will cause all but the first object to do the first statement
}
else
{
game.aColor = Color.Orange;
this.world.Translation = futurePosition.Translation;
}
}
//update actual bounding sphere last
this.myBoundingSphere = new BoundingSphere(this.GetWorld().Translation, 10f);
The second code block I have is the wholeCollidesWith method that I use to check collision between single objects. Please keep in mind that I am not currently using the otherWorld parameter, I had used it once before but stopped using it because I am updating each object's bounding sphere whenever its update method is called.
//Whole model collision, not checking individual meshes
public bool wholeCollidesWith(BoundingSphere futureBoundingSphere, BasicModel otherModel, Matrix otherWorld)
{
//Check if one object collides with another
if(futureBoundingSphere.Intersects(
otherModel.myBoundingSphere))
{
return true;
}
return false;
}
I am not sure what is going on but I am hoping that it is a simple syntax error that I am overlooking with my foreach loop. In any case I hope there will be someone who might be able to find the error that I could not find, please request for any more code/information if needed.