2014-02-15 113 views
1

我正在开发一款XNA平台游戏,并且需要一些与碰撞相关的帮助。游戏发生在一个洞穴中,问题在于艺术风格会粗略,因此地形(洞穴)会有所不同,所以我不能使用瓷砖。但我需要检查角色和洞穴上像素完美的碰撞,但是我无法弄清楚如何在无法在每个贴砖周围放置矩形的情况下如何操作,因为没有。没有瓷砖的2D游戏中的碰撞检测XNA

我曾经想过很多想出了一些想法:围绕整体水平

-One大的矩形和一个字符周围的和使用像素的完美碰撞。但是我不认为这会起作用,因为矩形也会包含背景。

- 手动展开矩形。非常丑陋的代码,可能会导致大量的错误和错误。

- 无论如何使用拼贴,并有数百种拼贴类型。再次,非常丑陋的代码,它只是看起来不对。

- 使用碰撞引擎。我最好从头开始制作游戏。

对不起,如果我解释不好,但这是一个相当复杂的问题(至少对我来说),我找不到任何解决方案。对于任何想法都会很高兴,谢谢。

回答

5

我认为你应该使用每像素碰撞检测来做你想做的事情。你可以有你的角色,并使他的纹理透明(使用图像的alpha)除了实际的角色。那么你可以拥有那个将成为你的洞穴的纹理。使洞穴的角色应该能够移动透明,这样你就可以拥有另一个纹理,它将成为整个关卡的背景。这里有一个粗略的例子:

字符(粉红色BG是透明的:)

enter image description here

洞(白色透明)

enter image description here

背景:

enter image description here

所有这三个加在一起:

enter image description here

这只是给你一个非常粗略的想法(因为我只是用Google搜索的背景和油漆画的洞穴)。然后,您可以使用洞穴纹理(不是洞穴背景)和角色纹理之间的alpha像素碰撞检测。有关如何轻松使用每像素冲突的教程,请参阅this。 HTH。这里有一些你可以使用的碰撞码(rectangleA应该是人物的矩形,dataA人物的像素数据,rectangleB洞穴的矩形(它可能是整个屏幕)和洞穴的像素数据(不是背景))由于您没有使用背景图像的像素数据,碰撞将不会与此数据检查:

/// <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; 
    } 
+0

@ user3313308,这有帮助吗? – davidsbro

+0

感谢您的回复@davidsbro!我仍然需要放置矩形,以便每个像素发生像素碰撞,对吧?还是我误解了每像素碰撞的概念? 如果我已经理解了它,它会检查两个矩形是否发生碰撞,然后检查矩形内的颜色以查看它是否发生碰撞。是对的吗?如果是这种情况,我是否仍然需要在洞穴周围放置长方形? – user3313308

+0

是的,你是对的@ user3313308。但你只需要有两个矩形;一个围绕整个洞穴纹理(可能是整个屏幕)和一个围绕着球员;你不应该需要两个以上。我提供的链接是一个非常简单的每像素碰撞项目,因此您可以了解它会是什么样子。 LMK如果有什么不清楚的话。 – davidsbro