我很难让我的碰撞检测算法正常工作。我正在从包含 0 和 1 的 .txt 中读取数据(0 是空格,1 不能通过)。我的算法有时会捕捉到有时它没有捕捉到并且最终不起作用。我当前的算法发布在下面,其中 sep 是一个分隔值,以防止我的精神重叠。
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;
}
帮助!