【发布时间】:2017-03-07 20:20:21
【问题描述】:
首先,我想说的是,我正在使用此代码进行每像素碰撞检测:
public bool CollidesWith(Sprite other)
{
// Default behavior uses per-pixel collision detection
return CollidesWith(other, true);
}
public bool CollidesWith(Sprite other, bool calcPerPixel)
{
// Get dimensions of texture
int widthOther = other.Texture.Width;
int heightOther = other.Texture.Height;
int widthMe = Texture.Width;
int heightMe = Texture.Height;
if (calcPerPixel && // if we need per pixel
((Math.Min(widthOther, heightOther) > 10) || // at least avoid doing it
(Math.Min(widthMe, heightMe) > 10))) // for small sizes (nobody will notice :P)
{
return Rectangle.Intersects(other.Rectangle) // If simple intersection fails, don't even bother with per-pixel
&& PerPixelCollision(this, other);
}
return Rectangle.Intersects(other.Rectangle);
}
public bool PerPixelCollision(Sprite a, Sprite b)
{
// Get Color data of each Texture
Color[] bitsA = new Color[a.Texture.Width * a.Texture.Height];
a.Texture.GetData(bitsA);
Color[] bitsB = new Color[b.Texture.Width * b.Texture.Height];
b.Texture.GetData(bitsB);
// Calculate the intersecting rectangle
int x1 = Math.Max(a.Rectangle.X, b.Rectangle.X);
int x2 = Math.Min(a.Rectangle.X + a.Rectangle.Width, b.Rectangle.X + b.Rectangle.Width);
int y1 = Math.Max(a.Rectangle.Y, b.Rectangle.Y);
int y2 = Math.Min(a.Rectangle.Y + a.Rectangle.Height, b.Rectangle.Y + b.Rectangle.Height);
// For each single pixel in the intersecting rectangle
for (int y = y1; y < y2; ++y)
{
for (int x = x1; x < x2; ++x)
{
// Get the color from each texture
Color a1 = bitsA[(x - a.Rectangle.X) + (y - a.Rectangle.Y) * a.Texture.Width];
Color b1 = bitsB[(x - b.Rectangle.X) + (y - b.Rectangle.Y) * b.Texture.Width];
if (a1.A != 0 && b1.A != 0) // If both colors are not transparent (the alpha channel is not 0), then there is a collision
{
return true;
}
}
}
// If no collision occurred by now, we're clear.
return false;
}
这段代码在我的“Sprite”结构中。它在 Windows、OpenGL(MonoGame 跨平台桌面项目)、Android 和 Windows UWP 上运行良好。
但在 iOS 上,当我调用 Sprite.CollidesWith(...); 时,我的程序会停止渲染屏幕。一切正常,但它不能渲染新帧(它渲染静态图像)。 (我添加了点击声音来测试程序是否崩溃。(点击屏幕冻结后,我可以听到声音)
问题出在这一行:
a.Texture.GetData(bitsA);
我在网上搜索,发现 Texture2D.GetData 没有在 iOS 上实现......所以,有没有可能在 iOS 上进行像素完美的碰撞检测? (不调用 GetData)
抱歉有任何错误,我是这个论坛的新手。 感谢您的帮助。
【问题讨论】:
-
@Jason 不,它不是重复的——我不想从 xml 加载它。保存或读取文件可能会影响游戏性能。
-
@Enter 再看看另一个问题。从 XML 加载是不是的答案。这样做的方法是创建您自己的 binary 格式(如其他问题的实际答案所示)。就性能而言,它不会对您在整个方案中的加载时间产生太大影响。加载该二进制格式可能只需要加载原始纹理所需时间的一小部分。
-
我没有说它是重复的,但它确实包含对缺少 iOS 实现的解决方法的讨论
标签: c# ios debugging xamarin.ios monogame