Search code examples
c#xnacollisionmonogameintersect

XNA (Monogame) I need a short way for collisions


I have a code which looks like this:

 /*Need  help here*/ 
if (car1.hitbox.Intersects(parkingLoot[0].hitbox) || car1.hitbox.Intersects(parkingLoot[1].hitbox))
        intersects = true;
    else
        intersects = false;

where hitboxes are a Rectangle. As you see there is 2 parkingLoot object in array and i checked them. But if i had 1000 parkingLoot objects? I dont want to use "for loop" to check every parkingLoot objects hitbox if intersects with car.

How to detect if car1.hitbox intersects with ANY HITBOX OF ANY OBJECT WHICH IS A PARKINGLOOT OBJECT


Solution

  • You can use the System.Linq extensions to iterate over the collection without foreach like below:

    var intersects = parkingLoot.Any(_ => car1.hitbox.Intersects(_.hitbox));
    

    or you can use the Parallel.ForEach from the System.Threading.Tasks to iterate over items in the list in parallel.