freshbm freshbm - 1 year ago 104
C# Question

Check for multiple overllaping sprites

I've just started exploring CocosSharp library for mobile games, and can't figure out if there is some easier way for detecting collision between sprites on screen.

I've watched some tutorials about collisions but can't find something about collision of multiple sprites.

I'm creating simple three to four balls bouncing on the screen and if they collide I want to bounce them. In tutorials they use BoundingBox.IntersectRect method for detection of collision but this is Ok for two elements on the screen:

bool doesBallOverlap = ball1.BoundingBoxTransformedToParent.IntersectsRect(ball2.BoundingBoxTransformedToParent);

but I think that this is an overkill if I have multiple elements on screen, in my case 3-4 balls. How can I effectively check for collision between them?

Answer Source

From Check if multiple rectangles intersect

If you get all Bounding boxes as rectangles here is what you can use

bool CheckIfAllIntersect(IEnumerable<Rect> rectangles)
    return rectangles.Aggregate(rectangles.FirstOrDefault(), Rect.Intersect) != Rect.Empty;

bool CheckIfAnyInteresect(IEnumerable<Rect> rectangles) 
    return rectangles.Any(rect => rectangles.Where(r => !r.Equals(rect)).Any(r => r.IntersectsWith(rect)));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download