Search code examples
c#algorithmcollision-detection

How could be done algorithm for rectangle collisions in C#


How could be done algorithm for Rectangle collisions on canvas in C#?

And which values of X,Y we should apply to avoid that collision?

Basically I have got two Rectangle in List so I just have to detect if there is a collision between them.

I am not sure if this is useful code The Liang-Barsky algorithm for line-rectangle collisions https://gist.github.com/ChickenProp/3194723

Thank you in advance!

enter image description here


Solution

  • You can use System.Windows.Rect.IntersectsWith. Try it like this:

    Rect rect1 = new Rect(left1, top1, widht1, height1);
    Rect rect2 = new Rect(left2, top2, widht2, height2);
    
    bool intersects = rect1.IntersectsWith(rect2);