Why my collision detection is not accurate?
- by optimisez
After trying and trying, I still cannot understand why the leg of character exceeds the wall but no clipping issue when I hit the wall from below. How should I fix it to make him standstill on the wall?
void initPlayer()
{
// Create texture.
hr = D3DXCreateTextureFromFileEx(d3dDevice, "player.png", 169, 44,
D3DX_DEFAULT, NULL, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED,
D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 255),
NULL, NULL, &player);
playerRect.left = playerRect.top = 0;
playerRect.right = 29;
playerRect.bottom = 36;
playerDest.X = 0;
playerDest.Y = 564;
playerDest.length = playerRect.right - playerRect.left;
playerDest.height = playerRect.bottom - playerRect.top;
}
void initBox()
{
hr = D3DXCreateTextureFromFileEx(d3dDevice, "brock.png", 330, 132,
D3DX_DEFAULT, NULL, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED,
D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 255),
NULL, NULL, &box);
boxRect.left = 33;
boxRect.top = 0;
boxRect.right = 63;
boxRect.bottom = 30;
boxDest.X = boxDest.Y = 300;
boxDest.length = boxRect.right - boxRect.left;
boxDest.height = boxRect.bottom - boxRect.top;
}
bool spriteCollide(Entity player, Entity target)
{
float left1, left2;
float right1, right2;
float top1, top2;
float bottom1, bottom2;
left1 = player.X;
left2 = target.X;
right1 = player.X + player.length;
right2 = target.X + target.length;
top1 = player.Y;
top2 = target.Y;
bottom1 = player.Y + player.height;
bottom2 = target.Y + target.height;
if (bottom1 < top2) return false;
if (top1 > bottom2) return false;
if (right1 < left2) return false;
if (left1 > right2) return false;
return true;
}
void collideWithBox()
{
if ( spriteCollide(playerDest, boxDest) && keyArr[VK_UP])
//playerDest.Y += 50;
playerDest.Y = boxDest.Y + boxDest.height;
else if ( spriteCollide(playerDest, boxDest) && !keyArr[VK_UP])
playerDest.Y = boxDest.Y - boxDest.height;
}