views:

201

answers:

3

Hi. I'm following an XNA tutorial and have the following code for collision detecting (detecting when a bullet collides with a target). Basically I'm looking to increment a score variable to display the score to the screen without re-writing the whole program. No matter where I place it in this method it seems to start incrementing from the number of targets, not from zero. Is there something simple I'm missing here? Any help would be greatly appreciated. Thanks.

private CollisionType CheckCollision(BoundingSphere sphere)
{
    if (completeCityBox.Contains(sphere) != ContainmentType.Contains)
        return CollisionType.Boundary;

    for (int i = 0; i < targetList.Count; i++)
    {
        if (targetList[i].Contains(sphere) != ContainmentType.Disjoint)
        {
            targetList.RemoveAt(i);
            i--;
            AddTargets();
            return CollisionType.Target;
        }
    }

    return CollisionType.None;
}
A: 

Assuming you're not incrementing / assigning the score variable anywhere else, and it's set to zero during initialization, the only other thing I can think of is that somehow you're triggering a collision with all of your objects - is that possible somehow, perhaps during the setup phase? Have you tried setting a breakpoint on your score increment line to see when it gets hit?

tzaman
+2  A: 

You could simply have a separate method called OnCollision() that updates the score (and could perform any physics for you if you wanted later on) and in your Update method, just have an if statement checking for collisions. Something like:

if( CheckCollision() == CollisionType.Target )
{
   OnCollision();
}

Hope that helps.

Ray

ray dey
A: 

if you are initialing it at the top of your class, and only incrementing it in the second if statement it sounds like the collision has to be happening with all items the first time.

without the rest of the code it might be hard to determine but for example in the AddTargets function if they start with the same location, and then are adjusted it could be possible that when this collision is checked they all qualified, or something of that nature.

As stated above, either set a break point when you update the score - if needed update it via a property and set a break point on the property so you can see where its being called and track back why it is being called. If its going from 0 to 250 before you actually have what you expect to be a collision, it should be easy to track down where the counter is being updated incorrectly, as it sounds its happening before what you expect to be your first collision and thus adding the first 250 points.

David Larrabee