Aha! It is done (finally)
Here is the function that detects the collision, and sets a vector accordingly.
vec2d Map::checkCollision(SDL_Rect obj)
{
vec2d vector;
vector.dirX = vector.dirY = vector.xMag = vector.yMag = 0;
if (data1.inRange(obj.y/TILE_DIM, obj.x/TILE_DIM)
&& data1[obj.y/TILE_DIM][obj.x/TILE_DIM] != 0)
{ // TOP LEFT
vector.dirX = ( (obj.x/TILE_DIM)*TILE_DIM+TILE_DIM ) - obj.x;
vector.dirY = ( (obj.y/TILE_DIM)*TILE_DIM+TILE_DIM ) - obj.y;
vector.xMag = 1;
vector.yMag = 1;
return vector;
}
if (data1.inRange(obj.y/TILE_DIM, (obj.x+obj.w)/TILE_DIM )
&& data1[obj.y/TILE_DIM][(obj.x+obj.w)/TILE_DIM] != 0)
{ // TOP RIGHT
vector.dirX = (obj.x + obj.w) - ((obj.x+obj.w)/TILE_DIM)*TILE_DIM;
vector.dirY = ( (obj.y/TILE_DIM)*TILE_DIM+TILE_DIM ) - obj.y;
vector.xMag = -1;
vector.yMag = 1;
return vector;
}
if (data1.inRange( ((obj.y+obj.h)/TILE_DIM), obj.x/TILE_DIM)
&& data1[((obj.y+obj.h)/TILE_DIM)][obj.x/TILE_DIM] != 0)
{ // BOTTOM LEFT
vector.dirX = ( (obj.x/TILE_DIM)*TILE_DIM+TILE_DIM ) - obj.x;
vector.dirY = (obj.y+obj.h) - ( (obj.y/TILE_DIM)*TILE_DIM+TILE_DIM );
vector.xMag = 1;
vector.yMag = -1;
return vector;
}
if (data1.inRange( ((obj.y+obj.h)/TILE_DIM), ((obj.x+obj.w)/TILE_DIM))
&& data1[((obj.y+obj.h)/TILE_DIM)][((obj.x+obj.w)/TILE_DIM)] != 0)
{ // BOTTOM RIGHT
vector.dirX = (obj.x + obj.w) - ((obj.x+obj.w)/TILE_DIM)*TILE_DIM;
vector.dirY = (obj.y+obj.h) - ( (obj.y/TILE_DIM)*TILE_DIM+TILE_DIM );
vector.xMag = -1;
vector.yMag = -1;
return vector;
}
return vector;
}
Then, to handle the output (what I have done so far, it is not perfect just yet)
motion = curMap.checkCollision(boundingBox);
if (motion.xMag != 0 || motion.yMag != 0)
{
if (abs(motion.dirX) < abs(motion.dirY))
{
x += motion.dirX * motion.xMag;
xVel=0;
}
else
{
y += motion.dirY * motion.yMag;
if (yVel > 0) jumping = false;
yVel=0;
}
}
It has one bug, if there is a block under the player and a block to the left of the player (or right I am assuming) and you move toward the left (or right) block, your player will fall through the block it is on. I know why this happens and I am trying to fix it...
You guys are probably shaking your head saying I overcomplicated it, but I just wanted really solid collision detection, and this is as solid as I can get it D;
Oh, another thing, this detection only works if the player's dimensions are smaller than or equal to (unsure on the equal) the blocks' dimensions.