This sounds like you're looking for basic AABB bounding box collision, which is essentially rather trivial.
Essentially you've got two similar problems here (the same problem in two different dimensions):
Determine whether two ranges overlap.
Why? Simple: If the ranges in one dimension overlap, both rectangles are at least in some way on the same height (i.e. next to each other; even if that distance is a bit far). If the ranges in both dimensions overlap, your rectangles overlap as well (i.e. they collide).
Determining whether two ranges in one dimension overlap is a rather trivial problem:
- The right border of rectangle
a must not be left of the left border of rectangle b. - The right border of rectangle
b must not be left of the left border of rectangle a. - If both conditions are true, the ranges overlap.
Applying this to both dimensions is rather easy:
collide_x = a.x + a.w > b.x && b.x + b.w > a.x; // collide horizontally collide_y = a.y + a.h > b.y && b.y + b.h > a.y; // collide vertically collide = collide_x && collide_y; // collide in both dimensions
Or, unified to check everything within one line:
collide = a.x + a.w > b.x && b.x + b.w > a.x && a.y + a.h > b.y && b.y + b.h > a.y;
Once this is done, you can simply compare the x and y coordinates to determine in which direction the collision happens. You can also calculate how far these overlap by doing some more math with coordinates, e.g. using something like this:
distance_x = min(abs(a.x + a.w - b.x), abs(b.x + b.w - a.x)); distance_y = min(abs(a.y + a.h - b.y), abs(b.y + b.h - a.y));