Here is how I do AABB collision detection. My entities have a Scale factor (1.0 is normal size). This code is available on programming2dgames.com
//=============================================================================
// Axis aligned bounding box collision detection method
// Called by collision()
// Pre: &ent = The other Entity.
// &collisionVector = Set by this function.
// Post: Returns true if collision, false otherwise.
// Sets collisionVector if collision. The collisionVector points in the
// direction of force that would be applied to this entity as a result
// of the collision. The magnitude of the collision vector is the
// distance the entities are overlapping.
//=============================================================================
bool Entity::collideBox(Entity &ent, VECTOR2 &collisionVector)
{
// if either entity is not active then no collision may occcur
if (!active || !ent.getActive())
return false;
// Check for collision using Axis Aligned Bounding Box
if ((this->getCenterX() + edge.right*getScale() >= ent.getCenterX() + ent.getEdge().left*ent.getScale()) &&
(this->getCenterX() + edge.left*getScale() <= ent.getCenterX() + ent.getEdge().right*ent.getScale()) &&
(this->getCenterY() + edge.bottom*getScale() >= ent.getCenterY() + ent.getEdge().top*ent.getScale()) &&
(this->getCenterY() + edge.top*getScale() <= ent.getCenterY() + ent.getEdge().bottom*ent.getScale()))
{
// If we get to here the entities are colliding. The edge with the smallest
// overlapping section is the edge where the collision is occurring.
// The collision vector is created perpendicular to the collision edge.
// Calculate amount of overlap between entities on each edge of box
float overlapX, overlapY;
if (this->getCenterX() < ent.getCenterX()) // if this entity left of other entity
{
overlapX = (this->getCenterX() + edge.right*getScale()) - (ent.getCenterX() + ent.getEdge().left*ent.getScale());
collisionVector = VECTOR2(-overlapX, 0); // collison vector points left
}
else // this entity right of other entity
{
overlapX = (ent.getCenterX() + ent.getEdge().right*ent.getScale()) - (this->getCenterX() + edge.left*getScale());
collisionVector = VECTOR2(overlapX, 0); // collison vector points right
}
if (this->getCenterY() < ent.getCenterY()) // if this entity above other entity
{
overlapY = (this->getCenterY() + edge.bottom*getScale()) - (ent.getCenterY() + ent.getEdge().top*ent.getScale());
if (overlapY < overlapX) // if Y overlap is smaller
collisionVector = VECTOR2(0, -overlapY); // collison vector points up
}
else // this entity below other entity
{
overlapY = (ent.getCenterY() + ent.getEdge().bottom*ent.getScale()) - (this->getCenterY() + edge.top*getScale());
if (overlapY < overlapX) // if Y overlap is smaller
collisionVector = VECTOR2(0, overlapY); // collison vector points down
}
return true; // entities are colliding
}
return false; // entities are not colliding
}