bool checkCollision( SDL_Rect A, SDL_Rect B )
{
//The sides of the rectangles
int leftA, leftB;
int rightA, rightB;
int topA, topB;
int bottomA, bottomB;
//Calculate the sides of rect A
leftA = A.x;
rightA = A.x + A.w;
topA = A.y;
bottomA = A.y + A.h;
//Calculate the sides of rect B
leftB = B.x;
rightB = B.x + B.w;
topB = B.y;
bottomB = B.y + B.h;
//If any of the sides from A are outside of B
if( bottomA <= topB )
{
return false;
}
if( topA >= bottomB )
{
return false;
}
if( rightA <= leftB )
{
return false;
}
if( leftA >= rightB )
{
return false;
}
//If none of the sides from A are outside B
return true;
}
void Player::Move( SDL_Rect solidCollisionBox )
{
//Move the Player left or right
collisionBox.x += xVel;
//If the Player went too far to the left or right
if( ( collisionBox.x < 0 ) || ( collisionBox.x + PLR_Width > SCR_Width ) || (checkCollision( collisionBox, solidCollisionBox ) ) )
{
//move back
collisionBox.x -= xVel;
}
//Move the Player up or down
collisionBox.y += yVel;
//If the Player went too far up or down
if( ( collisionBox.y < 0 ) || ( collisionBox.y + PLR_Height > SCR_Height ) || (checkCollision( collisionBox, solidCollisionBox ) ) )
{
//move back
collisionBox.y -= yVel;
}
}
MarauderIIC wrote:So... what's the problem, exactly?
RandomDever wrote:
I don't get it. and BTW in the vid i stop pressing the keyboard when i move up and randomly press when i'm stuck on the top.
That. He's not moving the character back far enough so that it isn't detected as a collision the next frame was my guess.
Re: Collision Detection Problems
Posted: Sat Jan 02, 2010 7:51 pm
by RandomDever
Well Actually the getting stuck on top thing was just me being a dumbass.
But I think I found an SDL library for collision so I'll see how that works.
Re: Collision Detection Problems
Posted: Sat Jan 02, 2010 9:47 pm
by ibly31
I don't know how you handle collision, but what I did was have a function that I sent the characters current position and where what direction they want to go.
like: void checkCol(PosX, PosY, AddX, AddY)
In my case, my character's size doesnt change so I don't need to have an entire SDL Rect. I then filtered through every collision rectangle and used lazyfoo's checkCollision function.
When handling the keys, I would do:
if(press left && checkCol(charX, charY, -1, 0)
if(press right && checkCol(charX, charY, 1, 0);