Collision detection
In games, we often need to check if objects touch or overlap. This is called collision detection. Saxion GameApp provides simple methods to check collisions between rectangles, circles, points, and combinations of these.
Rectangles
Rectangles are used for objects like platforms, walls, or hitboxes.
Check if two rectangles overlap
Use this method to see if two rectangles touch each other. Use the following parameters:
- x1, y1, w1, h1 – first rectangle (bottom-left corner x/y, width, height)
- x2, y2, w2, h2 – second rectangle
Rectangle contained by another rectangle
You can check if one rectangle is fully inside another retangle with the rectContainsRect method. You will need the following parameters:
- x1, y1, w1, h1 – outer rectangle
- x2, y2, w2, h2 – inner rectangle
Point inside rectangle
Check if a point is inside a rectangle. Use the parameters:
- px, py – coordinates of the point
- rx, ry, rw, rh – rectangle
Circles
Circles are useful for circular objects, explosions, or detection zones.
Check if two circles overlap
Parameters: - x1, y1, r1 – first circle (center and radius) - x2, y2, r2 – second circle
Point inside a circle
Check if a point is inside a circle. Use the parameters:
- px, py – point coordinates
- cx, cy, radius – circle
Rectangle and Circle
You can also check collisions between rectangles and circles.
Parameters:
- rectX, rectY, rectW, rectH – rectangle
- circleX, circleY, radius – circle
Advanced users: Rectangle, Circle, and Vector2
LibGDX has predefined classes for rectangles, circles and points. These classes (Rectangle, Circle and Vector2) can be used, since we have overloaded versions of the previous methods implemented as well.
| Shape | Class | Method Example |
|---|---|---|
| Rectangle | Rectangle |
GameApp.rectOverlap(rect1, rect2) |
| Circle | Circle |
GameApp.circleOverlap(circle1, circle2) |
| Point | Vector2 |
GameApp.pointInCircle(point, circle) or GameApp.pointInRect(point, rect) |
| Rect & Circle | Rectangle + Circle |
GameApp.rectCircleOverlap(rect, circle) |