在XNA中创建2D地狱主题直升机游戏。
我的逐像素碰撞检测有一些问题,因为当颜色不碰撞时,它会返回true。
这是我的每像素代码:
class PPCollisionDetection
{
public Rectangle rect1, rect2;
public Color[] data1, data2;
public PPCollisionDetection()
{
}
public Boolean Detect(Rectangle r1, Rectangle r2, Texture2D t1, Texture2D t2)
{
data1 = new Color[t1.Width * t1.Height];
t1.GetData(data1);
data2 = new Color[t2.Width * t2.Height];
t2.GetData(data2);
rect1 = r1;
rect2 = r2;
int top = Math.Max(rect1.Top, rect2.Top);
int bottom = Math.Min(rect1.Bottom, rect2.Bottom);
int left = Math.Max(rect1.Left, rect2.Left);
int right = Math.Min(rect1.Right, rect2.Right);
for (int y = top; y < bottom; y++)
for (int x = left; x < right; x++)
{
Color colour1 = data1[(x - rect1.Left) +
(y - rect1.Top) * rect1.Width];
Color colour2 = data2[(x - rect2.Left) +
(y - rect2.Top) * rect2.Width];
if (colour1.A != 0 && colour2.A != 0)
return true;
}
return false;
}
}
这就是我称之为Detect:的地方
if (new Rectangle((int)Helicopter.position.X,(int) Helicopter.position.Y,(int)Helicopter.HelicopterAnimation.Rectangle.Width,(int)Helicopter.HelicopterAnimation.Rectangle.Height).Intersects(stalagtiteRectangle))
{
if (collDetect.Detect(new Rectangle((int)Helicopter.position.X, (int)Helicopter.position.Y, (int)Helicopter.HelicopterAnimation.Rectangle.Width, (int)Helicopter.HelicopterAnimation.Rectangle.Height), stalagtiteRectangle, Helicopter.HelicopterAnimation.animation,
stalagtites))
{
touched = true;
}
else
{
touched = false;
}
}
您实际上并不需要第一个矩形碰撞,因为您已经在检查每像素碰撞了。
我认为应该是:
t1.GetData<Color>(data1);
t2.GetData<Color>(data2);