سؤال

I want to test if two BoundingBoxes intersect. I have a list:

List<BoundingBox> Mapa_BB = new List<BoundingBox>();

Then I add bounding boxes to this list, which works well – I tested it by changing it to a string and then drawing that – so I’m sure they exist. BoundingBox hero; is the bounding box of my hero.

Next, I made a function to test whether a collision occurred:

public void Collision()
{
    foreach (BoundingBox BB_map in Map_BB)
    {
        if (hero.Intersects(BB_map))
        { test = "true"; }
        else
        { test = "false"; }
    }
}

As you can see, if a collision occurred, I want to set string variable test to "true"; if not, to "false". I would think there’s something wrong with my list, but if I collide my hero with the last bounding box from the list, then it works well; for any other bounding box, it does not.

هل كانت مفيدة؟

المحلول

If you found an intersecting box, you need to break the foreach loop:

public void Colision()
{
    foreach (BoundingBox BB_map in Map_BB)
    {
        if (hero.Intersects(BB_map))
        {
            test = "true";
            break;
        }
        else
            test = "false";
    }
}

Without the break;, the following, non-matching boxes will set test back to "false".

نصائح أخرى

You don’t leave the loop when you’ve found a collision, and you overwrite test each time around the loop, so the only test that will actually apply (as you’ve noticed) is the last one.

In addition to that, the right way to do this is to return a boolean rather than using a global string representing a boolean. This also solves your problem. So:

public bool Collision() {
    foreach (BoundingBox BB_map in Map_BB) {
        if (hero.Intersects(BB_map)) {
            return true;
        }
    }

    return false;
}

Which could also be written as:

public bool Collision() {
    return Map_BB.Any(bb => hero.Intersects(bb));
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top