# Basic 2D Platformer Physics, Part 5: Object vs. Object Collision Detection

This post is part of a series called Basic 2D Platformer Physics .
Basic 2D Platformer Physics, Part 4
Basic 2D Platformer Physics, Part 6: Object vs. Object Collision Response

In this part of the series, we'll start working towards making it possible for objects to not only interact physically with the tilemap alone, but also with any other object, by implementing a collision detection mechanism between the game objects.

## Demo

The demo shows the end result of this tutorial. Use WASD to move the character. The middle mouse button spawns a one-way platform, the right mouse button spawns a solid tile, and the spacebar spawns a character clone. The sliders change the size of the player's character. The objects that detect a collision are made semi-transparent.

The demo has been published under Unity 5.4.0f3, and the source code is also compatible with this version of Unity.

## Collision Detection

Before we speak about any kind of collision response, such as making it impossible for the objects to go through each other, we first need to know whether those particular objects are overlapping.

This might be a very expensive operation if we simply checked each object against every other object in the game, depending on how many active objects the game currently needs to handle. So to alleviate our players' poor processor a little bit, we'll use...

### Spatial Partitioning!

This basically is splitting the game's space into smaller areas, which allows us to check the collisions between objects belonging only to the same area. This optimization is severely needed in games like Terraria, where the world and the number of possible colliding objects is huge and the objects are sparsely placed. In single-screen games, where the number of objects is heavily restricted by the size of the screen, it often is not required, but still useful.

#### The Method

The most popular spatial partitioning method for 2D space is quad tree; you can find its description in this tutorial. For my games, I'm using a flat structure, which basically means that the game space is split into rectangles of a certain size, and I'm checking for collisions with objects residing in the same rectangular space.

There's one nuance to this: an object can reside in more than one sub-space at a time. That's totally fine—it just means that we need to detect objects belonging to any of the partitions our former object overlaps with.

### Data for the Partitioning

The base is simple. We need to know how big each cell should be and a two-dimensional array, of which each element is a list of objects residing in a particular area. We need to place this data in the Map class.

 1 public int mGridAreaWidth = 16; 2 public int mGridAreaHeight = 16; 3 public List[,] mObjectsInArea;

In our case, I decided to express the size of the partition in tiles, and so each partition is 16 by 16 tiles big.

For our objects, we'll want a list of areas that the object is currently overlapping with, as well as its index in each partition. Let's add these to the MovingObject class.

 1 public List mAreas = new List(); 2 public List mIdsInAreas = new List();

Instead of two lists, we could use a single dictionary, but unfortunately the performance overhead of using complex containers in the current iteration of Unity leaves much to be desired, so we'll stick with the lists for the demo.

#### Initialize Partitions

Let's move on to calculate how many partitions we need to cover the entire area of the map. The assumption here is that no object can float outside the map bounds.

 1 mHorizontalAreasCount = Mathf.CeilToInt((float)mWidth / (float)mGridAreaWidth); 2 mVerticalAreasCount = Mathf.CeilToInt((float)mHeight / (float)mGridAreaHeight);

Of course, depending on the map size, the partitions need not exactly match the map bounds. That's why we're using a ceiling of calculated value to ensure we have at least enough to cover the whole map.

Let's initiate the partitions now.

 1 mObjectsInArea = new List[mHorizontalAreasCount, mVerticalAreasCount]; 2 3 for (var y = 0; y < mVerticalAreasCount; ++y) 4 { 5 for (var x = 0; x < mHorizontalAreasCount; ++x) 6 mObjectsInArea[x, y] = new List(); 7 }

Nothing fancy happening here—we just make sure that each cell has a list of objects ready for us to operate on.

### Assign Object's Partitions

Now it's time to make a function which will update the areas a particular object overlaps.

 1 public void UpdateAreas(MovingObject obj) 2 { 3 }

First off, we need to know which map tiles the object overlaps with. Since we're only using AABBs, all we need to check is what tile each corner of the AABB lands on.

 1 var topLeft = GetMapTileAtPoint(obj.mAABB.center + new Vector2(-obj.mAABB.HalfSize.x, obj.mAABB.HalfSizeY)); 2 var topRight = GetMapTileAtPoint(obj.mAABB.center + obj.mAABB.HalfSize); 3 var bottomLeft = GetMapTileAtPoint(obj.mAABB.center - obj.mAABB.HalfSize); 4 var bottomRight = new Vector2i();

Now to get the coordinate in the partitioned space, all we need to do is divide the tile position by the size of the partition. We don't need to calculate the bottom right corner partition right now, because its x coordinate will be equal to the top right corner's, and its y coordinate will be equal to the bottom left's.

 1 topLeft.x /= mGridAreaWidth; 2 topLeft.y /= mGridAreaHeight; 3 4 topRight.x /= mGridAreaWidth; 5 topRight.y /= mGridAreaHeight; 6 7 bottomLeft.x /= mGridAreaWidth; 8 bottomLeft.y /= mGridAreaHeight; 9 10 bottomRight.x = topRight.x; 11 bottomRight.y = bottomLeft.y;

This all should work based on the assumption that no object will be moved outside of the map bounds. Otherwise we'd need to have an additional check here to ignore the objects which are out of bounds.

Now, it is possible that the object resides entirely in a single partition, it may reside in two, or it can occupy the space right where four partitions meet. This is under the assumption that no object is bigger than the partition size, in which case it could occupy the whole map and all the partitions if it was big enough! I've been operating under this assumption, so that's how we're going to handle this in the tutorial. The modifications for allowing bigger objects are quite trivial, though, so I'll explain them as well.

Let's start by checking which areas the character overlaps with. If all the corner's partition coordinates are the same, then the object occupies just a single area.

 1 if (topLeft.x == topRight.x && topLeft.y == bottomLeft.y) 2 { 3 mOverlappingAreas.Add(topLeft); 4 }

If that's not the case and the coordinates are the same on the x-axis, then the object overlaps with two different partitions vertically.

 1 if (topLeft.x == topRight.x && topLeft.y == bottomLeft.y) 2 { 3 mOverlappingAreas.Add(topLeft); 4 } 5 else if (topLeft.x == topRight.x) 6 { 7 mOverlappingAreas.Add(topLeft); 8 mOverlappingAreas.Add(bottomLeft); 9 }

If we were supporting objects that are bigger than partitions, it'd be enough if we simply added all partitions from the top left corner to the bottom left one using a loop.

The same logic applies if only the vertical coordinates are the same.

 1 if (topLeft.x == topRight.x && topLeft.y == bottomLeft.y) 2 { 3 mOverlappingAreas.Add(topLeft); 4 } 5 else if (topLeft.x == topRight.x) 6 { 7 mOverlappingAreas.Add(topLeft); 8 mOverlappingAreas.Add(bottomLeft); 9 } 10 else if (topLeft.y == bottomLeft.y) 11 { 12 mOverlappingAreas.Add(topLeft); 13 mOverlappingAreas.Add(topRight); 14 }

Finally, if all the coordinates are different, we need to add all four areas.

 1 if (topLeft.x == topRight.x && topLeft.y == bottomLeft.y) 2 { 3 mOverlappingAreas.Add(topLeft); 4 } 5 else if (topLeft.x == topRight.x) 6 { 7 mOverlappingAreas.Add(topLeft); 8 mOverlappingAreas.Add(bottomLeft); 9 } 10 else if (topLeft.y == bottomLeft.y) 11 { 12 mOverlappingAreas.Add(topLeft); 13 mOverlappingAreas.Add(topRight); 14 } 15 else 16 { 17 mOverlappingAreas.Add(topLeft); 18 mOverlappingAreas.Add(bottomLeft); 19 mOverlappingAreas.Add(topRight); 20 mOverlappingAreas.Add(bottomRight); 21 }

Before we move on with this function, we need to be able to add and remove the object from a particular partition. Let's create these functions, starting with the adding.

 1 public void AddObjectToArea(Vector2i areaIndex, MovingObject obj) 2 { 3 var area = mObjectsInArea[areaIndex.x, areaIndex.y]; 4 5 //save the index of the object in the area 6 obj.mAreas.Add(areaIndex); 7 obj.mIdsInAreas.Add(area.Count); 8 9 //add the object to the area 10 area.Add(obj); 11 }

As you can see, the procedure is very simple—we add the index of the area to the object's overlapping areas list, we add the corresponding index to the object's ids list, and finally add the object to the partition.

Now let's create the removal function.

 1 public void RemoveObjectFromArea(Vector2i areaIndex, int objIndexInArea, MovingObject obj) 2 { 3 }

As you can see, we'll use the coordinates of the area that the character is no longer overlapping with, its index in the objects list within that area, and the reference to the object we need to remove.

To remove the object, we'll be swapping it with the last object in the list. This will require us to also make sure that the object's index for this particular area gets updated to the one our removed object had. If we did not swap the object, we would need to update the indexes of all the objects that go after the one we need to remove. Instead, we need to update only the one we swapped with.

Having a dictionary here would save a lot of hassle, but removing the object from an area is an operation that is needed far less frequently than iterating through the dictionary, which needs to be done every frame for every object when we are updating the object's overlapping areas.

 1 //swap the last item with the one we are removing 2 var tmp = area[area.Count - 1]; 3 area[area.Count - 1] = obj; 4 area[objIndexInArea] = tmp;

Now we need to find the area we are concerned with in the areas list of the swapped object, and change the index in the ids list to the index of the removed object.

 1 var tmpIds = tmp.mIdsInAreas; 2 var tmpAreas = tmp.mAreas; 3 for (int i = 0; i < tmpAreas.Count; ++i) 4 { 5 if (tmpAreas[i] == areaIndex) 6 { 7 tmpIds[i] = objIndexInArea; 8 break; 9 } 10 }

Finally, we can remove the last object from the partition, which now is a reference to the object we needed to remove.

 1 area.RemoveAt(area.Count - 1);

The whole function should look like this:

 1 public void RemoveObjectFromArea(Vector2i areaIndex, int objIndexInArea, MovingObject obj) 2 { 3 var area = mObjectsInArea[areaIndex.x, areaIndex.y]; 4 5 //swap the last item with the one we are removing 6 var tmp = area[area.Count - 1]; 7 area[area.Count - 1] = obj; 8 area[objIndexInArea] = tmp; 9 10 var tmpIds = tmp.mIdsInAreas; 11 var tmpAreas = tmp.mAreas; 12 for (int i = 0; i < tmpAreas.Count; ++i) 13 { 14 if (tmpAreas[i] == areaIndex) 15 { 16 tmpIds[i] = objIndexInArea; 17 break; 18 } 19 } 20 21 //remove the last item 22 area.RemoveAt(area.Count - 1); 23 }

Let's move back to the UpdateAreas function.

We know which areas the character overlaps this frame, but last frame the object already could have been assigned to the same or different areas. First, let's loop through the old areas, and if the object is no longer overlapping with them then let's remove the object from these.

 1 var areas = obj.mAreas; 2 var ids = obj.mIdsInAreas; 3 for (int i = 0; i < areas.Count; ++i) 4 { 5 if (!mOverlappingAreas.Contains(areas[i])) 6 { 7 RemoveObjectFromArea(areas[i], ids[i], obj); 8 //object no longer has an index in the area 9 areas.RemoveAt(i); 10 ids.RemoveAt(i); 11 --i; 12 } 13 }

Now let's loop through the new areas, and if the object hasn't been previously assigned to them, let's add them now.

 1 for (var i = 0; i < mOverlappingAreas.Count; ++i) 2 { 3 var area = mOverlappingAreas[i]; 4 if (!areas.Contains(area)) 5 AddObjectToArea(area, obj); 6 }

Finally, clear the overlapping areas list so it's ready to process the next object.

 1 mOverlappingAreas.Clear();

That's it! The final function should look like this:

 1 public void UpdateAreas(MovingObject obj) 2 { 3 //get the areas at the aabb's corners 4 var topLeft = GetMapTileAtPoint(obj.mAABB.center + new Vector2(-obj.mAABB.HalfSize.x, obj.mAABB.HalfSizeY)); 5 var topRight = GetMapTileAtPoint(obj.mAABB.center + obj.mAABB.HalfSize); 6 var bottomLeft = GetMapTileAtPoint(obj.mAABB.center - obj.mAABB.HalfSize); 7 var bottomRight = new Vector2i(); 8 9 topLeft.x /= mGridAreaWidth; 10 topLeft.y /= mGridAreaHeight; 11 12 topRight.x /= mGridAreaWidth; 13 topRight.y /= mGridAreaHeight; 14 15 bottomLeft.x /= mGridAreaWidth; 16 bottomLeft.y /= mGridAreaHeight; 17 18 bottomRight.x = topRight.x; 19 bottomRight.y = bottomLeft.y; 20 21 //see how many different areas we have 22 if (topLeft.x == topRight.x && topLeft.y == bottomLeft.y) 23 { 24 mOverlappingAreas.Add(topLeft); 25 } 26 else if (topLeft.x == topRight.x) 27 { 28 mOverlappingAreas.Add(topLeft); 29 mOverlappingAreas.Add(bottomLeft); 30 } 31 else if (topLeft.y == bottomLeft.y) 32 { 33 mOverlappingAreas.Add(topLeft); 34 mOverlappingAreas.Add(topRight); 35 } 36 else 37 { 38 mOverlappingAreas.Add(topLeft); 39 mOverlappingAreas.Add(bottomLeft); 40 mOverlappingAreas.Add(topRight); 41 mOverlappingAreas.Add(bottomRight); 42 } 43 44 var areas = obj.mAreas; 45 var ids = obj.mIdsInAreas; 46 47 for (int i = 0; i < areas.Count; ++i) 48 { 49 if (!mOverlappingAreas.Contains(areas[i])) 50 { 51 RemoveObjectFromArea(areas[i], ids[i], obj); 52 //object no longer has an index in the area 53 areas.RemoveAt(i); 54 ids.RemoveAt(i); 55 --i; 56 } 57 } 58 59 for (var i = 0; i < mOverlappingAreas.Count; ++i) 60 { 61 var area = mOverlappingAreas[i]; 62 if (!areas.Contains(area)) 63 AddObjectToArea(area, obj); 64 } 65 66 mOverlappingAreas.Clear(); 67 }

### Detect Collision Between Objects

First of all, we need to make sure to call UpdateAreas on all the game objects. We can do that in the main update loop, after each individual object's update call.

 1 void FixedUpdate() 2 { 3 for (int i = 0; i < mObjects.Count; ++i) 4 { 5 switch (mObjects[i].mType) 6 { 7 case ObjectType.Player: 8 case ObjectType.NPC: 9 ((Character)mObjects[i]).CustomUpdate(); 10 mMap.UpdateAreas(mObjects[i]); 11 break; 12 } 13 } 14 }

Before we create a function in which we check all collisions, let's create a struct which will hold the data of the collision.

This will be very useful, because we'll be able to preserve the data as it is at the time of collision, whereas if we saved only the reference to an object we collided with, not only would we have too little to work with, but also the position and other variables could have changed for that object before the time we actually get to process the collision in the object's update loop.

 1 public struct CollisionData 2 { 3 public CollisionData(MovingObject other, Vector2 overlap = default(Vector2), Vector2 speed1 = default(Vector2), Vector2 speed2 = default(Vector2), Vector2 oldPos1 = default(Vector2), Vector2 oldPos2 = default(Vector2), Vector2 pos1 = default(Vector2), Vector2 pos2 = default(Vector2)) 4 { 5 this.other = other; 6 this.overlap = overlap; 7 this.speed1 = speed1; 8 this.speed2 = speed2; 9 this.oldPos1 = oldPos1; 10 this.oldPos2 = oldPos2; 11 this.pos1 = pos1; 12 this.pos2 = pos2; 13 } 14 15 public MovingObject other; 16 public Vector2 overlap; 17 public Vector2 speed1, speed2; 18 public Vector2 oldPos1, oldPos2, pos1, pos2; 19 }

The data which we save is the reference to the object we collided with, the overlap, the speed of both objects at the time of collision, their positions, and also their positions just before the time of collision.

Let's move to the MovingObject class and create a container for the freshly created collision data which we need to detect.

 1 public List mAllCollidingObjects = new List();

Now let's go back to the Map class and create a CheckCollisions function. This will be our heavy duty function where we detect the collisions between all the game objects.

 1 public void CheckCollisions() 2 { 3 }

To detect the collisions, we'll be iterating through all the partitions.

 1 for (int y = 0; y < mVerticalAreasCount; ++y) 2 { 3 for (int x = 0; x < mHorizontalAreasCount; ++x) 4 { 5 var objectsInArea = mObjectsInArea[x, y]; 6 } 7 }

For each partition, we'll be iterating through every object within it.

 1 for (int y = 0; y < mVerticalAreasCount; ++y) 2 { 3 for (int x = 0; x < mHorizontalAreasCount; ++x) 4 { 5 var objectsInArea = mObjectsInArea[x, y]; 6 for (int i = 0; i < objectsInArea.Count - 1; ++i) 7 { 8 var obj1 = objectsInArea[i]; 9 } 10 } 11 }

For each object, we check every other object that is further down the list in the partition. This way we'll check each collision only once.

 1 for (int y = 0; y < mVerticalAreasCount; ++y) 2 { 3 for (int x = 0; x < mHorizontalAreasCount; ++x) 4 { 5 var objectsInArea = mObjectsInArea[x, y]; 6 for (int i = 0; i < objectsInArea.Count - 1; ++i) 7 { 8 var obj1 = objectsInArea[i]; 9 for (int j = i + 1; j < objectsInArea.Count; ++j) 10 { 11 var obj2 = objectsInArea[j]; 12 } 13 } 14 } 15 }

Now we can check whether the AABBs of the objects are overlapping each other.

 1 Vector2 overlap; 2 3 for (int y = 0; y < mVerticalAreasCount; ++y) 4 { 5 for (int x = 0; x < mHorizontalAreasCount; ++x) 6 { 7 var objectsInArea = mObjectsInArea[x, y]; 8 for (int i = 0; i < objectsInArea.Count - 1; ++i) 9 { 10 var obj1 = objectsInArea[i]; 11 for (int j = i + 1; j < objectsInArea.Count; ++j) 12 { 13 var obj2 = objectsInArea[j]; 14 15 if (obj1.mAABB.OverlapsSigned(obj2.mAABB, out overlap)) 16 { 17 } 18 } 19 } 20 } 21 }

Here's what happens in the AABB's OverlapsSigned function.

 1 public bool OverlapsSigned(AABB other, out Vector2 overlap) 2 { 3 overlap = Vector2.zero; 4 5 if (HalfSizeX == 0.0f || HalfSizeY == 0.0f || other.HalfSizeX == 0.0f || other.HalfSizeY == 0.0f 6 || Mathf.Abs(center.x - other.center.x) > HalfSizeX + other.HalfSizeX 7 || Mathf.Abs(center.y - other.center.y) > HalfSizeY + other.HalfSizeY) return false; 8 9 overlap = new Vector2(Mathf.Sign(center.x - other.center.x) * ((other.HalfSizeX + HalfSizeX) - Mathf.Abs(center.x - other.center.x)), 10 Mathf.Sign(center.y - other.center.y) * ((other.HalfSizeY + HalfSizeY) - Mathf.Abs(center.y - other.center.y))); 11 12 return true; 13 }

As you can see, if an AABB's size on any axis is zero, it cannot be collided with. The other thing you could notice is that even if the overlap is equal to zero, the function will return true, as it will reject the cases in which the gap between the AABBs is larger than zero. That's mainly because if the objects are touching each other and not overlapping, we still want to have the information that this is the case, so we need this to go through.

As the last thing, once the collision is detected, we calculate how much the AABB overlaps with the other AABB. The overlap is signed, so in this case if the overlapping AABB is on this AABB's right side, the overlap on the x axis will be negative, and if the other AABB is on this AABB's left side, the overlap on the x axis will be positive. This will make it easy later on to come out of the overlapping position, as we know in which direction we want the object to move.

Moving back to our CheckCollisions function, if there was no overlap, that's it, we can move to the next object, but if an overlap occurred then we need to add the collision data to both objects.

 1 if (obj1.mAABB.OverlapsSigned(obj2.mAABB, out overlap)) 2 { 3 obj1.mAllCollidingObjects.Add(new CollisionData(obj2, overlap, obj1.mSpeed, obj2.mSpeed, obj1.mOldPosition, obj2.mOldPosition, obj1.mPosition, obj2.mPosition)); 4 obj2.mAllCollidingObjects.Add(new CollisionData(obj1, -overlap, obj2.mSpeed, obj1.mSpeed, obj2.mOldPosition, obj1.mOldPosition, obj2.mPosition, obj1.mPosition)); 5 }

To make things easy for us, we'll assume that the 1's (speed1, pos1, oldPos1) in the CollisionData structure always refer to the owner of the collision data, and the 2's are the data concerning the other object.

The other thing is, the overlap is calculated from the obj1's perspective. The obj2's overlap needs to be negated, so if obj1 needs to move left to move out of the collision, obj2 will need to move right to move out of the same collision.

There's still one small thing to take care of—because we're iterating through the map's partitions and one object can be in multiple partitions at the same, up to four in our case, it's possible that we'll detect an overlap for the same two objects up to four times.

To remove this possibility, we simply check whether we've already detected a collision between two objects. If that's the case, we skip the iteration.

 1 if (obj1.mAABB.OverlapsSigned(obj2.mAABB, out overlap) && !obj1.HasCollisionDataFor(obj2)) 2 { 3 obj1.mAllCollidingObjects.Add(new CollisionData(obj2, overlap, obj1.mSpeed, obj2.mSpeed, obj1.mOldPosition, obj2.mOldPosition, obj1.mPosition, obj2.mPosition)); 4 obj2.mAllCollidingObjects.Add(new CollisionData(obj1, -overlap, obj2.mSpeed, obj1.mSpeed, obj2.mOldPosition, obj1.mOldPosition, obj2.mPosition, obj1.mPosition)); 5 }

The HasCollisionDataFor function is implemented as follows.

 1 public bool HasCollisionDataFor(MovingObject other) 2 { 3 for (int i = 0; i < mAllCollidingObjects.Count; ++i) 4 { 5 if (mAllCollidingObjects[i].other == other) 6 return true; 7 } 8 9 return false; 10 }

It simply iterates through all the collision data structures and looks up whether any already belong to the object we are about to check collision for.

This should be fine in general use case as we're not expecting an object to collide with many other objects, so looking through the list is going to be quick. However, in a different scenario it might be better to replace the list of CollisionData with a dictionary, so instead of iterating we could tell right away if an element is already in or not.

The other thing is, this check saves us from adding multiple copies of the same collision to the same list, but if the objects are not colliding, we'll anyway be checking for overlap multiple times if both objects belong to the same partitions.

This shouldn't be a big concern, as the collision check is cheap and the situation is not that common, but if it were a problem, the solution might be to simply have a matrix of checked collisions or a two-way dictionary, fill it up as the collisions get checked, and reset it right before we call the CheckCollisions function.

Now let's call the function we just finished in the main game loop.

 1 void FixedUpdate() 2 { 3 for (int i = 0; i < mObjects.Count; ++i) 4 { 5 switch (mObjects[i].mType) 6 { 7 case ObjectType.Player: 8 case ObjectType.NPC: 9 ((Character)mObjects[i]).CustomUpdate(); 10 mMap.UpdateAreas(mObjects[i]); 11 mObjects[i].mAllCollidingObjects.Clear(); 12 break; 13 } 14 } 15 16 mMap.CheckCollisions(); 17 }

That's it! Now all our objects should have the data about the collisions.

To test if everything works properly, let's make it so that if a character collides with an object, the character's sprite will turn semi-transparent.

As you can see, the detection seems to be working well!

## Summary

That's it for another part of the simple 2D platformer physics series. We managed to implement a very simple spatial partitioning mechanism and detect the collisions between each object.

If you have a question, a tip on how to do something better, or just have an opinion on the tutorial, feel free to use the comment section to let me know!