Skip to content

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
boolean overlap = GameApp.rectOverlap(x1, y1, w1, h1, x2, y2, w2, h2);

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
boolean contained = GameApp.rectContainsRect(x1, y1, w1, h1, x2, y2, w2, h2);

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
boolean inside = GameApp.pointInRect(px, py, rx, ry, rw, rh);

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

boolean overlap = GameApp.circleOverlap(x1, y1, r1, x2, y2, r2);

Point inside a circle

Check if a point is inside a circle. Use the parameters:

  • px, py – point coordinates
  • cx, cy, radius – circle
boolean inside = GameApp.pointInCircle(px, py, cx, cy, radius);

Rectangle and Circle

You can also check collisions between rectangles and circles.

Parameters:

  • rectX, rectY, rectW, rectH – rectangle
  • circleX, circleY, radius – circle
boolean overlap = GameApp.rectCircleOverlap(rectX, rectY, rectW, rectH, circleX, circleY, radius);

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)