【发布时间】:2013-11-08 20:19:21
【问题描述】:
我无法让我的碰撞检测算法正常工作。我正在从包含 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;
}
救命!
【问题讨论】:
-
您能否更清楚地了解究竟是什么不起作用?它有时只是不检测 X 碰撞,还是不检测 Y 碰撞,或两者兼而有之?还是它检测到碰撞但不阻止玩家在“空间”中移动?
-
从最好的情况来看,我可以说它有时并没有检测到它在其他地方没有检测到它创建的墙。我的玩家能够穿过一些他们不应该能够穿过的墙壁,而其他人则被实际上没有绘制的墙壁挡住了..
标签: c# xna collision-detection