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

Tags: C++, help, physics, platformer, walls

Comments

demize
07. Oct 2008 · 00:58 UTC
Hmm… If the player has a floor below them, then don’t let them move down. All it takes is: if(player.y != floor.y+z){(insert your downwards movement code here)}. Replace z with how much you move per frame, and change this to support how you’re doing it.
wonderwhy-er
07. Oct 2008 · 07:43 UTC
Not enough info it seems… Is it only floor or there are walls. Is it platformer style where you can jump trough some platforms etc etc. More info please :)
07. Oct 2008 · 17:38 UTC
I usually have a ‘grounded’ variable on objects, and a conditional splits up what movement I allow it before input and collision, where I may need to move the object again or change its grounded variable for the next tick (or whatever you call a timer event) ^_^
SpaceManiac
07. Oct 2008 · 18:51 UTC
Only walls – no platforms you can sometimes go through. I’m thinking of the kind of walls in Ninja Kitty Vs. The Nukebots. They way the cat hits the walls in that game is almost exactly what I’m looking for.