# Collision detection in 2D games.

I'm doing a basic 2D platform game. I want to get the Relative position of one rectangle to another..

This is how I do it right now:

``````const float offset = 5;
yes (x1 <= x2 && x1 + w1 >= x2)
{
if (Math.Abs ​​(y1 + h1 - y2) <= offset)
back CollisionType.Top;
else if (Math.Abs ​​(y1 - h2 - y2) <= offset)
back CollisionType.Bottom;
yes no ((y1 <= y2 && y1 + h1 >= y2) || (y1> = y2 && y1 <= y2 + h2))
back CollisionType.Left;
}
yes (x2 <= x1 && x2 + w2 >= x1)
{
if (Math.Abs ​​(y1 + h1 - y2) <= offset)
back CollisionType.Top;
else if (Math.Abs ​​(y1 - h2 - y2) <= offset)
back CollisionType.Bottom;
yes no ((y1 <= y2 && y1 + h1 >= y2) || (y1> = y2 && y1 <= y2 + h2))
back CollisionType.Right;
}

returns CollisionType.NoCollision;
``````

Here's how this function works (or at least how I suppose it works):

Using this function, I often have collision errors, but I can not understand a global rule of when it happens. I do not think a lot of `Yes` The blocks would solve the problem.

I need a collision detection function that receives two type arguments `Entity` (The class can contain any field or function, but it must have an X, a Y, a width and a height) The function needs to return the relative Position of the first rectangle to the second.

What improvements would you suggest to my current function? or Is there a better system for collision detection in 2D games where you need to get a relative position instead of a simple `true False`?