My Journey...
I've long struggled with rectangle to rectangle collision resolution. I've been making games for almost 10 years and still have yet to find a foolproof, reliable strategy.
When doing research on 2d, rectangle to rectangle collision resolution, I find myself digging through piles of collision detection, or other topics that have nothing to do with my search for truth (circle to rectangle, other detection methods...) For me, detecting collision has never been the issue...
if player.x + player.width > box.x and
player.x < box.x + box.width and
player.y + player.height > box.y and
player.y < box.y + box.height then
// A collision has been detected...
// But now I am lost.....
Assuming both the player and box objects are positioned at their upper left corner
The Rectangular Paradox...
For those brave enough, there is the path of chaos, torture, and unknown horrors available... The road known as "creating your own". I have chosen to walk this path many times, never to find the answers I'm looking for. I'm sure I share some quarrels of this road with fellow developers.
At first you might think it a simple task: "Once you know the rectangles are overlapping, how difficult can it really be to push one out of the other?" Oh boy, how I miss that sweet innocence...
Let us say, the player in the above example is falling down on top of the box, and we want it to stop and be pushed back to the top of the box. Easy, right? We can just do a simple check if the player is above the box, and if so, push him up to the top.
// We know the player is overlapping with the box..
if player.y < box.y then
player.y = box.y - player.height
Done. Tested and proven to work. But, let's say now we want the player to stop at the left side of the box..
if player.x < box.x then
player.x = box.x - player.width
Looks like it should work fine right? But no. Upon testing you move the player to collide with the left side of the box, and bam. Suddenly, he has immediately moved to the top of the box.
Why? The player can be both above the box, and to the left of the box at the same time. So one seems to end up always being favored over the others. To mitigate this I have written 3 nested if statements, 50 line chunks of code for each side of the rectangle, and wasted near weeks of my life..
Conclusion
Although I walk my journey alone - I know there are others, battling the same demonic mystery of rectangle to rectangle collision resolution. And also.. Those who have conquered it...
I'm hoping someone can help me understand their solidified, proven methods of resolution. To help me and any other developers reading this right now, become level 100 devs.