0

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?

Petter Hesselberg
  • 5,062
  • 2
  • 24
  • 42
freshbm
  • 5,540
  • 5
  • 46
  • 75

1 Answers1

1

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)));
}
Community
  • 1
  • 1
Yuri S
  • 5,355
  • 1
  • 15
  • 23
  • Thanks, this directed me in some direction but this only tells me that some of my sprites are overlapping but not witch or how many and I need to know that to make corresponding 'bouncing' of intersecting sprites. I will upvote this, but I can't mark it as answer. – freshbm Nov 13 '16 at 18:48
  • the only way to find out what you want is to implement a loop. Let me know if you need help with that but the loop is pretty simple – Yuri S Nov 13 '16 at 18:50
  • Thanks, I was afraid of that :) I just wanted to know is there any other way to do that – freshbm Nov 13 '16 at 18:57
  • May be you can write complicated LINQ and get list of what you need but I am almost positive it will work slower than a loop. – Yuri S Nov 13 '16 at 19:12