Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

libGDX, detect side touching between rectangles (side collision)

I use libGDX library for my game. I user overlap method for detecting collision detection between two rectangles.

...
if (r1.overlaps(r2)) collisionTest();
...

I want to detect touching side on rectangle (top, bottom, left or right):

r1 overlap r2 on the left side

Can anyone give me code for this, but this need to be fast method.

Thanks

like image 469
Jovan Avatar asked Oct 22 '25 22:10

Jovan


1 Answers

You can use the method intersectRectangles provided in the Intersector class to determine if two rectangles are overlapping, and if so, where they overlap. You could use this info to determine if they overlap with the left, right, top, and/or bottom.

Rectangle r1 = /*Initialize*/;                             
Rectangle r2 = /*Initialize*/;                             
Rectangle intersection = new Rectangle();                  
Intersector.intersectRectangles(r1, r2, intersection);     
if(intersection.x > r1.x)                                  
    //Intersects with right side                              
if(intersection.y > r1.y)                                  
    //Intersects with top side                                
if(intersection.x + intersection.width < r1.x + r1.width)  
    //Intersects with left side                               
if(intersection.y + intersection.height < r1.y + r1.height)
    //Intersects with bottom side    
like image 56
kabb Avatar answered Oct 25 '25 10:10

kabb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!