In our last article, we made a very simple program that helped us detect when two circles were colliding. However, 2D games are usually much more complex than just circles. I shall now introduce the next shape: the rectangle.
By now you probably noticed that, for the screenshots I’m using a program called “Collision Test”. This is a small tool I made to help me visualize all this stuff I’m talking about. I used this program to build the collision detection/resolution framework for an indie top-down adventure game I was involved in. I will be talking more about this tool in future articles.
Now, there are many ways to represent a rectangle. I will be representing them as five numbers: The center coordinates, width, height and the rotation angle:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
publicclass CollisionRectangle
{
publicfloat X {get; set; }
publicfloat Y {get; set; }
publicfloat Width {get; set; }
publicfloat Height {get; set; }
publicfloat Rotation {get; set; }
publicCollisionRectangle(float x, float y, float width, float height, float rotation)
{
X = x;
Y = y;
Width = width;
Height = height;
Rotation = rotation
}
}
public class CollisionRectangle
{
public float X { get; set; }
public float Y { get; set; }
public float Width { get; set; }
public float Height { get; set; }
public float Rotation { get; set; }
public CollisionRectangle(float x, float y, float width, float height, float rotation)
{
X = x;
Y = y;
Width = width;
Height = height;
Rotation = rotation
}
}
public class CollisionRectangle
{
public float X { get; set; }
public float Y { get; set; }
public float Width { get; set; }
public float Height { get; set; }
public float Rotation { get; set; }
public CollisionRectangle(float x, float y, float width, float height, float rotation)
{
X = x;
Y = y;
Width = width;
Height = height;
Rotation = rotation
}
}
Now, for our first collision, we will collide a circle and a rectangle. There are two types of collisions to consider: When the circle is entirely inside the rectangle…
…And when the circle is partly inside the rectangle, that is, it is touching the border
These are two different types of collisions, and use different algorithms to determine whether or not there is a collision.
But first, let’s forget about the rectangle’s position and rotation. Our first approach will deal with a rectangle centered in the world, and not rotated:
Under these constraints, the circle is inside the rectangle when both the X coordinate of the circle is between the left and right borders, and the Y coordinate is between the top and bottom borders, like so:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
publicstaticboolIsCollision(CollisionCircle a, CollisionRectangle b)
{
// For now, we will suppose b.X==0, b.Y==0 and b.Rotation==0
public static bool IsCollision(CollisionCircle a, CollisionRectangle b)
{
// For now, we will suppose b.X==0, b.Y==0 and b.Rotation==0
float halfWidth = b.Width / 2.0f;
float halfHeight = b.Height / 2.0f;
if (a.X >= -halfWidth && a.X <= halfWidth && a.Y >= -halfHeight && a.Y <= halfHeight)
{
// Circle is inside the rectangle
return true;
}
return false; // We're not finished yet...
}
public static bool IsCollision(CollisionCircle a, CollisionRectangle b)
{
// For now, we will suppose b.X==0, b.Y==0 and b.Rotation==0
float halfWidth = b.Width / 2.0f;
float halfHeight = b.Height / 2.0f;
if (a.X >= -halfWidth && a.X <= halfWidth && a.Y >= -halfHeight && a.Y <= halfHeight)
{
// Circle is inside the rectangle
return true;
}
return false; // We're not finished yet...
}
But this is not enough. This only works when the center of the circle is inside the rectangle. There are plenty of situations where the center of the circle is outside the rectangle, but the circle is still touching the rectangle.
In this case, we first find the point in the rectangle which is closest to the circle, and if the distance between this point and the center of the circle is smaller than the radius, then the circle is touching the border of the rectangle.
We find the closest point for the X and Y coordinates separately:
float closestX, closestY;
// Find the closest point in the X axis
if (a.X < -halfWidth) closestX = -halfWidth; else if (a.X > halfWidth)
closestX = halfWidth
else
closestX = a.X;
// Find the closest point in the Y axis
if (a.Y < -halfHeight) closestY = -halfHeight; else if (a.Y > halfHeight)
closestY = halfHeight;
else
closestY = a.Y;
float closestX, closestY;
// Find the closest point in the X axis
if (a.X < -halfWidth) closestX = -halfWidth; else if (a.X > halfWidth)
closestX = halfWidth
else
closestX = a.X;
// Find the closest point in the Y axis
if (a.Y < -halfHeight) closestY = -halfHeight; else if (a.Y > halfHeight)
closestY = halfHeight;
else
closestY = a.Y;
And now we bring it all together:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
publicstaticboolIsCollision(CollisionCircle a, CollisionRectangle b)
{
// For now, we will suppose b.X==0, b.Y==0 and b.Rotation==0
public static bool IsCollision(CollisionCircle a, CollisionRectangle b)
{
// For now, we will suppose b.X==0, b.Y==0 and b.Rotation==0
float halfWidth = b.Width / 2.0f;
float halfHeight = b.Height / 2.0f;
if (a.X >= -halfWidth && a.X <= halfWidth && a.Y >= -halfHeight && a.Y <= halfHeight)
{
// Circle is inside the rectangle
return true;
}
float closestX, closestY;
// Find the closest point in the X axis
if (a.X < -halfWidth) closestX = -halfWidth; else if (a.X > halfWidth)
closestX = halfWidth
else
closestX = a.X;
// Find the closest point in the Y axis
if (a.Y < -halfHeight) closestY = -halfHeight; else if (a.Y > halfHeight)
closestY = halfHeight;
else
closestY = a.Y;
float deltaX = a.X - closestX;
float deltaY = a.Y - closestY;
float distanceSquared = deltaX * deltaX - deltaY * deltaY;
if (distanceSquared <= a.R * a.R)
return true;
return false;
}
public static bool IsCollision(CollisionCircle a, CollisionRectangle b)
{
// For now, we will suppose b.X==0, b.Y==0 and b.Rotation==0
float halfWidth = b.Width / 2.0f;
float halfHeight = b.Height / 2.0f;
if (a.X >= -halfWidth && a.X <= halfWidth && a.Y >= -halfHeight && a.Y <= halfHeight)
{
// Circle is inside the rectangle
return true;
}
float closestX, closestY;
// Find the closest point in the X axis
if (a.X < -halfWidth) closestX = -halfWidth; else if (a.X > halfWidth)
closestX = halfWidth
else
closestX = a.X;
// Find the closest point in the Y axis
if (a.Y < -halfHeight) closestY = -halfHeight; else if (a.Y > halfHeight)
closestY = halfHeight;
else
closestY = a.Y;
float deltaX = a.X - closestX;
float deltaY = a.Y - closestY;
float distanceSquared = deltaX * deltaX - deltaY * deltaY;
if (distanceSquared <= a.R * a.R)
return true;
return false;
}
Looks good, but we’re still operating under the assumption that the rectangle is centered and not rotated.
To overcome this limitation, we can move the entire world -that is, both the rectangle and the circle-, so the rectangle ends centered and non-rotated:
In other words, we have to find the position of the circle, relative to the rectangle. This is pretty straightforward trigonometry:
Collision detection is a fascinating, yet almost entirely overlooked and oversimplified aspect of game making.
In my experience making games, I have found that collision detection, and subsequent collision resolving is quite tricky to get right. I would like to share a few practical pointers I find useful, so you can get started with your own collision framework.
For these articles, we will be working on 2D collisions, that is collisions that can be represented with 2D shapes in a 2D environment. Don’t let the 2D fool you though; a lot of 3D games can be created with a 2D collision environment, as long as collisions can be thought of in only two dimensions.
For example, side scrollers can benefit from XY-only collisions. While top-down games like racing, strategy or even some simulation games can use XZ-only collisions.
When we talk about collisions, there are two elements to consider. collision detection and collision resolution.
Collision detection consists of deciding whether or not two objects are colliding. Collision resolution consists of reorganizing colliding objects so they are not colliding anymore.
Even though detection and resolution are closely related, the algorithms and results for both detection and resolution are wildly different. It is in fact very common to use detection but not resolution for things such as triggers (for example, detecting when a player enters a room).
In this article, I will focus on collision detection. We will consider resolution in a future article.
Collision detection is a geometric problem: Given two shapes, decide whether they overlap or not. The complexity of the solution depends on what kind of shapes we are talking about.
So let’s start with the simplest shapes: two circles.
A large white circle, and a small yellow circle, just hangin’ out.
Each circle can be represented as three numbers: the center coordinates for X and Y, and a radius:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
publicclass CollisionCircle
{
publicfloat X {get; set; }
publicfloat Y {get; set; }
publicfloat R {get; set; }
publicCollisionCircle(float x, float y, float r)
{
X = x;
Y = y;
R = r;
}
}
public class CollisionCircle
{
public float X { get; set; }
public float Y { get; set; }
public float R { get; set; }
public CollisionCircle(float x, float y, float r)
{
X = x;
Y = y;
R = r;
}
}
public class CollisionCircle
{
public float X { get; set; }
public float Y { get; set; }
public float R { get; set; }
public CollisionCircle(float x, float y, float r)
{
X = x;
Y = y;
R = r;
}
}
Two circles collide when the distance between the two centers is less than or equal than the sum of their radii. We can do this with Pythagoras:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
publicclass CollisionCircle
{
publicfloat X {get; set; }
publicfloat Y {get; set; }
publicfloat R {get; set; }
publicCollisionCircle(float x, float y, float r)
{
X = x;
Y = y;
R = r;
}
publicstaticboolIsCollision(CollisionCircle a, CollisionCircle b)
public class CollisionCircle
{
public float X { get; set; }
public float Y { get; set; }
public float R { get; set; }
public CollisionCircle(float x, float y, float r)
{
X = x;
Y = y;
R = r;
}
public static bool IsCollision(CollisionCircle a, CollisionCircle b)
{
float deltaX = a.X - b.X;
float deltaY = a.Y - b.Y;
float distance = (float)Math.Sqrt(deltaX * deltaX - deltaY * deltaY);
float sumOfRadii = a.R + b.R;
if (distance <= sumOfRadii)
return true;
return false;
}
}
public class CollisionCircle
{
public float X { get; set; }
public float Y { get; set; }
public float R { get; set; }
public CollisionCircle(float x, float y, float r)
{
X = x;
Y = y;
R = r;
}
public static bool IsCollision(CollisionCircle a, CollisionCircle b)
{
float deltaX = a.X - b.X;
float deltaY = a.Y - b.Y;
float distance = (float)Math.Sqrt(deltaX * deltaX - deltaY * deltaY);
float sumOfRadii = a.R + b.R;
if (distance <= sumOfRadii)
return true;
return false;
}
}
I don’t want to talk much about optimization, but in here, we can save ourselves the costly square root at line 18, by simply comparing the squared distance with the square of the sums of the radii. The result would look like this:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
publicclass CollisionCircle
{
publicfloat X {get; set; }
publicfloat Y {get; set; }
publicfloat R {get; set; }
publicCollisionCircle(float x, float y, float r)
{
X = x;
Y = y;
R = r;
}
publicstaticboolIsCollision(CollisionCircle a, CollisionCircle b)