# How can I align a 2D object properly using tilemap collision [duplicate]

I'm making a mario clone, and I have been working on the collision but I can never seem to get it right.
I started out with "true/false" collision, aligning the player at it's last position, and as can guess, the results were barely ok. The problem was in the alignment and in the direction of movement.
I then converted my collision function to return the rectangle area of intersection as shown in the top left corner: (Yellow rectangle)

I now have a bunch of other problems which I think are more acceptable to solve.
I'm unsure of what to do with the data I get from the function now.

My current logic is this:

// Update Gravity
// Update Movement
// Check for collision
// Intersect2 applies offset to a existing rectangle, and returns true or false.
if(Intersect2(*level, *camera)) // Check collision against level, but only against tiles in camera view.
{
// Correct Y Movement
if (offset.height >= 16) sprite.move(0, offset.height); // 16 is half a tile size
else
{
sprite.move(0, -offset.height);
inAir = false;
}
velocity.y = 0;

// We corrected Y, are we still intersecting? then correct X as well
if(Intersect2(*level, *camera))
{
if (offset.width >= 16) sprite.move(offset.width, 0); // 16 is half a tile size
else sprite.move(0, -offset.height);
velocity.x = 0;
}
// Reset the offset rectangle
offset.height = 0;
offset.top = 0;
offset.left = 0;
offset.width = 0;
}


How can I apply the offset in a correct way? Side note: I have stuttering problems while on ground, as my gravity is always "on" so that I can fall down when walking off an elevated block.

• I think the term for what you're attempting might be discrete collision resolution between two axis-aligned bounding boxes (AABBs). Is that page helpful -- particularly Figure 3? Is your objective to snap Mario the shortest distance out of the obstacle? – Anko Mar 21 '14 at 19:59
• Yes I want to snap him to the shortest distance out of the object ( which should result in correct collision from all angles ). And I the webpage wasen't very helpful to me :( – Pontus Magnusson Mar 21 '14 at 20:25
• Your stuttering walking on the ground problem maybe because you are calling your collision detection before your movement, trying placing your collision detection logic at the bottom of your update method. – Canvas Mar 31 '14 at 17:57