I am having difficulties getting my collision detection algorithm to work properly. I am reading in data from a .txt that contains 0s and 1s (0s are empty spaces 1s cannot be walked through). My algorithm catches sometimes other times it doesn't and ultimately is not working. My current algorithm is posted below where sep is a separation value to keep my spirits from overlapping.
private void collisionDetect()
{
float diffxleft, diffxright, diffytop, diffybottom;
float diffx, diffy;
hit = false;
foreach (Block b in blocks)
{
if (hit)
break;
if (inside(charPos, sep, b))
{
hit = true;
diffxleft = Math.Abs(charPos.X + sep - b.pos.X);
diffxright = Math.Abs(charPos.X - sep - (b.pos.X + b.rect.Width));
diffytop = Math.Abs(charPos.Y + sep - b.pos.Y);
diffybottom = Math.Abs(charPos.Y - sep - (b.pos.Y + b.rect.Height));
diffx = Math.Min(diffxleft, diffxright);
diffy = Math.Min(diffytop, diffybottom);
if (diffx < diffy)
{
charVel.X = 0;
if (diffxleft < diffxright)
charPos.X = b.pos.X - sep;
else
charPos.X = b.pos.X + b.rect.Width + sep;
}
else
{
charVel.Y = 0;
if (diffytop < diffybottom)
charPos.Y = b.pos.Y - sep;
else
charPos.Y = b.pos.Y + b.rect.Height + sep;
}
}
}
foreach (Block b in blocks)
{
b.disp.X = b.pos.X + 10 - bkgdisplay.X;
b.disp.Y = 470 - b.pos.Y;
}
charPosDisp.X = charPos.X - bkgdisplay.X;
charPosDisp.Y = 480 - charPos.Y;
}
Help!