A.I, Data and Software Engineering

Basic shapes collision detection without complicated maths

B

This article demonstrates the collision between square, circle, and points using Android Kotlin. We will focus on the programming aspect rather than using complicated mathematical equations. A video tutorial is at the end of the article.

Two rectangle collision

Collision Detection - game development

Using complicated math for rectangle collision is not always necessary. Java and Kotlin offer a convenient way to detect the collision with intersect method.

The approach is useful for game development where objects bounds are rectangles.

Two circle collision

Collision Detection - Happy Coding
Two circle collsion

To detect the collision of two circles, we need to check whether the Euclidean distance between two center points is smaller than the sum of the two radii. In Java and Kotlin, there is no circle class, so we can create one.

Rectangle and Circle collision detection

XNA/Monogame Detecting collision between Circle and Rectangle not working -  Stack Overflow

This one is a little bit more complicated. We will divide it into 2 main cases:

  1. The center of the circle is inside the rectangle (very easy and always collide)
  2. The center of the circle is outside the rectangle: we consider the distance of the center to the nearest edge of the rectangle (left, right, top, bottom)

In the following code, we use the same definition for the Circle class. For the first case, we use contains method to verify whether the center of circle c1 is inside the rectangle r1.

Point inside/outside Rectangle or Circle

The detection is useful if you want to detect the touch location is inside a certain area. For rectangle, the solution is a one-liner. The following code detects touch in the onTouchEvent method.

For the circle, the same technique with two circle collision detection is applied. We need to check the distance of clicked point and the center point is smaller than the radius.

Video tutorial (Kotlin)

Enjoy 10 min exclusive video to create custom views and collision detection.

Useful links

Add comment

A.I, Data and Software Engineering

PetaMinds focuses on developing the coolest topics in data science, A.I, and programming, and make them so digestible for everyone to learn and create amazing applications in a short time.

Pin It on Pinterest

Newsletters

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

Petaminds will use the information you provide on this form to be in touch with you and to provide updates.