Collisions

I need help with collision code. I want to keep the player from falling through floors, pretty much. Help?

EDIT: Okay, I’ve got some good collision detection, but there’s something wrong with my moving code.

bool checkCollision(SDL_Rect &movable, double &vx, double &vy, SDL_Rect solid, bool move) {

int moveLeft = movable.x;

int moveTop = movable.y;

int moveRight = moveLeft + movable.w;

int moveBottom = moveTop + movable.h;

int solidLeft = solid.x;

int solidTop = solid.y;

int solidRight = solidLeft + solid.w;

int solidBottom = solidTop + solid.h;

int clipLeft = max(moveLeft, solidLeft);

int clipTop = max(moveTop, solidTop);

int clipRight = min(moveRight, solidRight);

int clipBottom = min(moveBottom, solidBottom);

if(clipLeft == clipRight || clipTop == clipBottom)

return false;

if(!move)

return true;

int clipWidth = clipRight – clipLeft;

int clipHeight = clipBottom – clipTop;

if(clipWidth solidX) {

// moving to right

movable.x += solidRight – moveLeft;

} else {

// moving to left

movable.x -= moveRight – solidLeft;

}

} else {

// moving along y axis

vy = 0;

int moveY = moveTop + movable.h / 2;

int solidY = solidLeft + solid.h / 2;

if(moveY > solidY) {

// moving to bottom

movable.y += solidBottom – moveTop;

} else {

// moving to top

movable.y -= moveBottom – solidTop;

}

}

return true;

}

Please help! If you’re interested in seeing what’s happening, here’s the program: http://files.chocoboheaven.com/uploads/Guests/files/85267_PaintWorld.zip

Source: ludumdare.com archive

Found a bug?
Tell us on Discord