use*_*308 1 c# xna collision-detection pixel-perfect tile
我正在开发一个XNA平台游戏,需要一些关于碰撞的帮助.游戏发生在洞穴中,问题是艺术风格会粗略,因此地形(洞穴)会有很多不同,所以我不能使用瓷砖.但是我需要检查角色和洞穴上的像素完美碰撞,但是当我无法在每个瓷砖周围放置矩形时,我无法弄清楚如何做到这一点,因为没有.
我想到了很多想法:
- 围绕整个关卡的一个大矩形和围绕角色的一个大矩形,并使用像素完美碰撞.但我认为这不会起作用,因为矩形也会包含背景.
- 手动放置矩形.非常难看的代码,可能会导致很多错误和错误.
- 无论如何使用瓷砖,有数百种瓷砖类型.再次,非常丑陋的代码,它似乎错了.
- 使用碰撞引擎.我最好从头开始制作游戏.
我很抱歉,如果我解释得很糟糕,但这是一个相当复杂的问题(至少对我来说),我无法在网上找到任何解决方案.对任何想法都会很高兴,谢谢.
我认为你应该使用每像素碰撞检测来做你想做的事情.你可以拥有你的角色,并使他的纹理透明(使用图像alpha)除了实际角色.然后你可以拥有terrain你的洞穴纹理.使角色的部分角色应该能够透明移动,这样你就可以拥有另一个纹理,它将成为整个关卡的背景.这是一个粗略的例子:
性格(粉红色的BG是透明的:)

洞穴(白色是透明的)

背景:

这三个加在一起:

这只是为了给你一个非常粗略的想法(因为我只是用谷歌搜索背景并在油漆区画出洞穴).然后你可以在洞穴纹理(不是洞穴背景)和角色纹理之间使用alpha像素碰撞检测.有关如何轻松使用每像素冲突的教程,请参阅此内容.HTH.这里有一些你可以使用的碰撞代码(rectangleA应该是角色的矩形,dataA角色的像素数据,rectangleB洞穴的矩形(可能是整个屏幕),以及dataB洞穴的像素数据(不是背景))如果不使用背景图像的像素数据,则不会使用此数据检查碰撞:
/// <param name="rectangleA">Bounding rectangle of the first sprite</param>
/// <param name="dataA">Pixel data of the first sprite</param>
/// <param name="rectangleB">Bouding rectangle of the second sprite</param>
/// <param name="dataB">Pixel data of the second sprite</param>
/// <returns>True if non-transparent pixels overlap; false otherwise</returns>
static bool IntersectPixels(Rectangle rectangleA, Color[] dataA,
Rectangle rectangleB, Color[] dataB)
{
// Find the bounds of the rectangle intersection
int top = Math.Max(rectangleA.Top, rectangleB.Top);
int bottom = Math.Min(rectangleA.Bottom, rectangleB.Bottom);
int left = Math.Max(rectangleA.Left, rectangleB.Left);
int right = Math.Min(rectangleA.Right, rectangleB.Right);
// Check every point within the intersection bounds
for (int y = top; y < bottom; y++)
{
for (int x = left; x < right; x++)
{
// Get the color of both pixels at this point
Color colorA = dataA[(x - rectangleA.Left) +
(y - rectangleA.Top) * rectangleA.Width];
Color colorB = dataB[(x - rectangleB.Left) +
(y - rectangleB.Top) * rectangleB.Width];
// If both pixels are not completely transparent,
if (colorA.A != 0 && colorB.A != 0)
{
// then an intersection has been found
return true;
}
}
}
// No intersection found
return false;
}
Run Code Online (Sandbox Code Playgroud)