## Practical 2D collision detection – Part 2

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:

```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:

```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;```

And now we bring it all together:

```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:

```float relativeX = a.X - b.X;
float relativeY = a.Y - b.Y;
float relativeDistance = (float)Math.Sqrt(relativeX * relativeX + relativeY * relativeY);
float relativeAngle = (float)Math.Atan2(relativeY, relativeX);
float newX = relativeDistance * (float)Math.Cos(relativeAngle - b.Rotation);
float newY = relativeDistance * (float)Math.Sin(relativeAngle - b.Rotation);```

And then put it all together:

```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 static bool IsCollision(CollisionCircle a, CollisionRectangle b)
{
float relativeX = a.X - b.X;
float relativeY = a.Y - b.Y;
float relativeDistance = (float)Math.Sqrt(relativeX * relativeX + relativeY * relativeY);
float relativeAngle = (float)Math.Atan2(relativeY, relativeX);
float newX = relativeDistance * (float)Math.Cos(relativeAngle - b.Rotation);
float newY = relativeDistance * (float)Math.Sin(relativeAngle - b.Rotation);
float halfWidth = b.Width / 2.0f;
float halfHeight = b.Height / 2.0f;

if (newX >= -halfWidth && newX <= halfWidth && newY >= -halfHeight && newY <= halfHeight)
{
// Circle is inside the rectangle
return true;
}

float closestX, closestY;
// Find the closest point in the X axis
if (newX < -halfWidth) closestX = -halfWidth; else if (newX > halfWidth)
closestX = halfWidth
else
closestX = newX;

// Find the closest point in the Y axis
if (newY < -halfHeight) closestY = -halfHeight; else if (newY > halfHeight)
closestY = halfHeight;
else
closestY = newY;

float deltaX = newX - closestX;
float deltaY = newY - closestY;
float distanceSquared = deltaX * deltaX - deltaY * deltaY;

if (distanceSquared <= a.R * a.R)
return true;

return false;
}
}

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 static bool IsCollision(CollisionCircle a, CollisionRectangle b)
{
float relativeX = a.X - b.X;
float relativeY = a.Y - b.Y;
float relativeDistance = (float)Math.Sqrt(relativeX * relativeX + relativeY * relativeY);
float relativeAngle = (float)Math.Atan2(relativeY, relativeX);
float newX = relativeDistance * (float)Math.Cos(relativeAngle - b.Rotation);
float newY = relativeDistance * (float)Math.Sin(relativeAngle - b.Rotation);
float halfWidth = b.Width / 2.0f;
float halfHeight = b.Height / 2.0f;

if (newX >= -halfWidth && newX <= halfWidth && newY >= -halfHeight && newY <= halfHeight)
{
// Circle is inside the rectangle
return true;
}

float closestX, closestY;
// Find the closest point in the X axis
if (newX < -halfWidth) closestX = -halfWidth; else if (newX > halfWidth)
closestX = halfWidth
else
closestX = newX;

// Find the closest point in the Y axis
if (newY < -halfHeight) closestY = -halfHeight; else if (newY > halfHeight)
closestY = halfHeight;
else
closestY = newY;

float deltaX = newX - closestX;
float deltaY = newY - closestY;
float distanceSquared = deltaX * deltaX - deltaY * deltaY;

if (distanceSquared <= a.R * a.R)
return true;

return false;
}
}```

In the next article, we’ll put some structure to all of this.

## Practical 2D collision detection – Part 1

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.

Each circle can be represented as three numbers: the center coordinates for X and Y, and a radius:

```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:

```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;
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:

```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 distanceSquared = deltaX * deltaX - deltaY * deltaY;
float sumOfRadii = a.R + b.R;
return true;
return false;
}
}```

So far, so good. On the next article, we’ll figure out how to do collision detection with other kinds of shapes.

## Faking coroutines in C# – Part 1

Note: As of C# 5.0, the language natively supports coroutines using async and await. This is still useful if you’re in a limited environment where you don’t have these cool language features.

I happen to love coroutines. When making games, you sometimes want to start a task that takes some time to complete. Let’s consider a simple task: when a button is pressed, wait for 1 second, play a sound, wait for 1 more second and then play another sound.

So let’s consider you have a task manager, something like this:

```List<Func<bool>> tasks;
//...
{
}```

So let’s implement our task. State machines are very useful for doing this kind of stuff. Say something like this:

```tasks.Add(delegate bool() // I happen to prefer this syntax to the lambda one
{
if (buttonPressed) // Whatever that does
{
int framesLeft = 0;
int state = 0;
{
switch (state)
{
case 0:
framesLeft = 60;
state = 1;
break;
case 1:
framesLeft--;
if (framesLeft <= 0)
{
PlaySound(soundA);
framesLeft = 60;
state = 1;
}
break;
case 2:
framesLeft--;
if (framesLeft <= 0)
{
PlaySound(soundB);
framesLeft = 60;
return false;
}
break;
}
return true;
});
}
return true;
});```

So yeah, it works, but it’s not really straightforward. More complex tasks will have dozens of states, jumping back to previous states, or you may even have state machines inside state machines inside state machines. I’ve seen this happen more often than I’d like, and it usually results in 20 levels of indentation on a 5000 line method.

There has to be an easier way to do this. How about if the task were something like:

```tasks.Add(delegate bool() // I happen to prefer this syntax to the lambda one
{
if (buttonPressed) // Whatever that does
{
int framesLeft = 0;
int state = 0;
{
Wait(60);
PlaySound(soundA);
Wait(60);
PlaySound(soundB);
return false; // ?
});
}
return true;
});```

If those Wait() calls block, then the entire task scheduler will stop. However, if they don’t block, then they’re not really waiting. What to do?

A naive solution is to use the OS task scheduler, and create a thread for each task you have, and make the wait calls block. This seems to work, but concurrency becomes a problem. You don’t know when the OS scheduler will switch from task to task, and using variables across threads will require some kind of locking.

There is however, a better way to do this. Some languages (notoriously lua) provide coroutines. That is, a piece of code, that can yield to other pieces of code. In our example, it would be something like this:

```tasks.Add(delegate bool() // I happen to prefer this syntax to the lambda one
{
if (buttonPressed) // Whatever that does
{
int framesLeft = 0;
int state = 0;
{
for (int k = 0; K < 60; k++)
yield return true
PlaySound(soundA);
for (int k = 0; K < 60; k++)
yield return true
PlaySound(soundB);
yield return false;
});
}
yield return true;
});```

Notice that instead of return statements, we now have yield return. The idea is that the function temporarily returns a value, but the next time the same piece of code is called, instead of starting once again from the top (like usual functions), it will resume from where we yielded, and every local variable will retain its value.

This creates the illusion of multithreading, without requiring any kind of synchronization, as everything is running on the same thread. This is called “cooperative multitasking”, because you choose when one task yields to another one. This is in contrast to “preemptive multitasking”, in which threads get suspended at arbitrary points.

Unfortunately, you can’t do that in C#. Well, let me rephrase that. You -can- do several things, but it doesn’t get as pretty as I wrote it above.

A way to implement this is with iterators. Instead of a Func<bool>, we wrap it into an IEnumerable<, and yield from it as if it were an iterator. Unfortunately, you can’t yield from inside an anonymous function.

In fact, C# 5 offers a new pair of keyords: async and await, which can be used to create blocks like these, but when I had to solve this problem, C# 5 wasn’t out yet (in fact, I still use Visual Studio 2010), so I needed a solution without these new awesome features.

I found a blog post somewhere (I’ll post it here if I find it again) that suggested faking coroutines using threads, and manually synchronizing them using monitors. Unfortunately, it didn’t provide any code, so I had to come up with a solution of my own.

In the next post, I will show you how to use threads and semaphores to fake coroutines. In order for it to work like real coroutines, we must guarantee that only one thread will be running at a given time, and therefore simulate a cooperative multitasking environment using preemptive multitasking.

## How to do UDP hole punching

I will now show you how to do UDP hole punching, with code in C. Hole punching is an advanced networking concept, so you’re expected to at least know how to compile/run this code.

I have written lots of comments inside the code to explain what is happening.

To use this, run the server code in a computer with a public IP address, and then run the client code in two or more different computers, each behind a different NAT.

I compiled and tested this on Ubuntu Server 11.04 and CentOS 5, it should work easily in probably all other linuces and BSDs. It could run in Windows using the WSA code. This code is also not endianness-safe, so it would be best to run it on x86-64 or similar in all machines.

I release this code to the public domain, but you’re a complete lunatic if you plan to use this code in any real program.

server code:

```// UDP hole punching example, server code
// Base UDP code stolen from http://www.abc.se/~m6695/udp.html
// By Oscar Rodriguez
// This code is public domain, but you're a complete lunatic
// if you plan to use this code in any real program.

#include <arpa/inet.h>
#include <netinet/in.h>
#include
#include <sys/types.h>
#include <sys/socket.h>
#include
#include
#include
#define BUFLEN 512
#define NPACK 10
#define PORT 9930

// A small struct to hold a UDP endpoint. We'll use this to hold each client's endpoint.
struct client
{
int host;
short port;
};

// Just a function to kill the program when something goes wrong.
void diep(char *s)
{
perror(s);
exit(1);
}

int main(void)
{
int s, i, j, slen=sizeof(si_other);
char buf[BUFLEN];
struct client clients[10]; // 10 clients. Notice that we're not doing any bound checking.
int n = 0;
// Create a UDP socket
if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
diep("socket");
// si_me stores our local endpoint. Remember that this program
// has to be run in a network with UDP endpoint previously known
// and directly accessible by all clients. In simpler terms, the
// server cannot be behind a NAT.
memset((char *) &si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(PORT);
diep("bind");
while (1)
{
// When a new client sends a datagram...
if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr*)(&si_other), &slen)==-1)
diep("recvfrom");
// The client's public UDP endpoint data is now in si_other.
// Notice that we're completely ignoring the datagram payload.
// If we want to support multiple clients inside the same NAT,
// we'd have clients send their own private UDP endpoints
// encoded in some way inside the payload, and store those as
// well.
// Now we add the client's UDP endpoint in our list.
clients[n].port = si_other.sin_port;
n++;
// And then tell everybody about everybody's public UDP endpoints
for (i = 0; i < n; i++)
{
si_other.sin_port = clients[i].port;
// We send a datagram for each client in our list. Of course,
// we could also assemble a single datagram and send that.
for (j = 0; j < n; j++)
{
// The payload is the client's public UDP endpoint, clients[j]
// We're sending binary data here, using the server's byte order.
// In your code, you should make sure every client agrees on the endianness.
if (sendto(s, &clients[j], 6, 0, (struct sockaddr*)(&si_other), slen)==-1)
diep("sendto");
}
}
printf("Now we have %d clients\n", n);
// And we go back to listening. Notice that since UDP has no notion
// of connections, we can use the same socket to listen for data
// from different clients.
}
// Actually, we never reach this point...
close(s);
return 0;
}
```

client code:

```// UDP hole punching example, client code
// Base UDP code stolen from http://www.abc.se/~m6695/udp.html
// By Oscar Rodriguez
// This code is public domain, but you're a complete lunatic
// if you plan to use this code in any real program.

#include <arpa/inet.h>
#include <netinet/in.h>
#include
#include <sys/types.h>
#include <sys/socket.h>
#include
#include
#include
#define BUFLEN 512
#define NPACK 10
#define PORT 9930

// This is our server's IP address. In case you're wondering, this one is an RFC 5737 address.
#define SRV_IP "203.0.113.61"

// A small struct to hold a UDP endpoint. We'll use this to hold each peer's endpoint.
struct client
{
int host;
short port;
};

// Just a function to kill the program when something goes wrong.
void diep(char *s)
{
perror(s);
exit(1);
}

int main(int argc, char* argv[])
{
int s, i, f, j, k, slen=sizeof(si_other);
struct client buf;
struct client server;
struct client peers[10]; // 10 peers. Notice that we're not doing any bound checking.
int n = 0;
if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
diep("socket");
// Our own endpoint data
memset((char *) &si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(PORT); // This is not really necessary, we can also use 0 (any port)
// The server's endpoint data
memset((char *) &si_other, 0, sizeof(si_other));
si_other.sin_family = AF_INET;
si_other.sin_port = htons(PORT);
diep("aton");
// Store the server's endpoint data so we can easily discriminate between server and peer datagrams.
server.port = si_other.sin_port;
// Send a simple datagram to the server to let it know of our public UDP endpoint.
// Not only the server, but other clients will send their data through this endpoint.
// The datagram payload is irrelevant, but if we wanted to support multiple
// clients behind the same NAT, we'd send our won private UDP endpoint information
// as well.
if (sendto(s, "hi", 2, 0, (struct sockaddr*)(&si_other), slen)==-1)
diep("sendto");
// Right here, our NAT should have a session entry between our host and the server.
// We can only hope our NAT maps the same public endpoint (both host and port) when we
// send datagrams to other clients using our same private endpoint.
while (1)
{
// Receive data from the socket. Notice that we use the same socket for server and
// peer communications. We discriminate by using the remote host endpoint data, but
// remember that IP addresses are easily spoofed (actually, that's what the NAT is
// doing), so remember to do some kind of validation in here.
if (recvfrom(s, &buf, sizeof(buf), 0, (struct sockaddr*)(&si_other), &slen)==-1)
diep("recvfrom");
{
// The datagram came from the server. The server code is set to send us a
// datagram for each peer, in which the payload contains the peer's UDP
// endpoint data. We're receiving binary data here, sent using the server's
// byte ordering. We should make sure we agree on the endianness in any
// serious code.
f = 0;
// Now we just have to add the reported peer into our peer list
for (i = 0; i < n && f == 0; i++)
{
if (peers[i].host == buf.host && peers[i].port == buf.port)
{
f = 1;
}
}
// Only add it if we didn't have it before.
if (f == 0)
{
peers[n].host = buf.host;
peers[n].port = buf.port;
n++;
}
si_other.sin_port = buf.port;
printf("Now we have %d peers\n", n);
// And here is where the actual hole punching happens. We are going to send
// a bunch of datagrams to each peer. Since we're using the same socket we
// previously used to send data to the server, our local endpoint is the same
// as before.
// If the NAT maps our local endpoint to the same public endpoint
// regardless of the remote endpoint, after the first datagram we send, we
// have an open session (the hole punch) between our local endpoint and the
// peer's public endpoint. The first datagram will probably not go through
// the peer's NAT, but since UDP is stateless, there is no way for our NAT
// to know that the datagram we sent got dropped by the peer's NAT (well,
// our NAT may get an ICMP Destination Unreachable, but most NATs are
// configured to simply discard them) but when the peer sends us a datagram,
// it will pass through the hole punch into our local endpoint.
for (k = 0; k < 10; k++)
{
// Send 10 datagrams.
for (i = 0; i < n; i++)
{
si_other.sin_port = peers[i].port;
// Once again, the payload is irrelevant. Feel free to send your VoIP
// data in here.
if (sendto(s, "hi", 2, 0, (struct sockaddr*)(&si_other), slen)==-1)
diep("sendto()");
}
}
}
else
{
// The datagram came from a peer
for (i = 0; i < n; i++)
{
// Identify which peer it came from
if (peers[i].host == buf.host && peers[i].port == (short)(buf.port))
{
break;
}
}
// It is possible to get data from an unregistered peer. These are some reasons
// I quickly came up with, in which this can happen:
// 1. The server's datagram notifying us with the peer's address got lost,
//    or it hasn't arrived yet (likely)
// 2. A malicious (or clueless) user is sending you data on this endpoint (maybe
//    unlikely)
// 3. The peer's public endpoint changed either because the session timed out,
//    or because its NAT did not assign the same public endpoint when sending
//    datagrams to different remote endpoints. If this happens, and we're able
//    to detect this situation, we could change our peer's endpoint data to
//    the correct one. If we manage to pull this off correctly, even if at most
//    one client has a NAT that doesn't support hole punching, we can communicate
//    directly between both peers.
}
}]
// Actually, we never reach this point...
close(s);
return 0;
}```