【问题标题】:What's the easiest way to implement collision detection in an XNA Game w/ C#?在带有 C# 的 XNA 游戏中实现碰撞检测的最简单方法是什么?
【发布时间】:2011-01-19 03:11:29
【问题描述】:

我基本上是在制作 Pong 克隆,我想添加碰撞。我希望它的工作方式是,每个桨将被分成 4 个部分(不是视觉上的),并且球会根据它击中的部分做出不同的反应。

就碰撞而言,我只知道矩形碰撞,这基本上是整个桨的整体。我不知道怎么做,所以桨有 4 个可能的碰撞点,不同的反应。

【问题讨论】:

    标签: c# xna


    【解决方案1】:

    只需将桨分成 4 块,并保持为一体 :)

    Collide 方法返回 -1 如果矩形没有碰撞,或者第一个碰撞索引。

    CollideIndex 方法返回碰撞矩形的 IEnumerable 索引。 ;)

    Paddle p;
    World w;
    Ball b;
    
    Rect[] paddleSections = new Rect[] 
    {
      p.Section[0],
      p.Section[1],
      p.Section[2],
      p.Section[3],
    }
    
    Rect[] worldSections = new Rect[] 
    {
      new Rect(p.Top, p.Left, p.Right, p.Bottom) // just simple world, for example
    }
    
    Rect[] ballSections = new Rect[] 
    {
      new Rect(p.Top, p.Left, p.Right, p.Bottom) // just one ball piece, for example
    }
    
    Rect[] bricksSection = GetBrickRects();
    
    int index = 0;
    if ((index = Collide(ballSections, worldSections) != -1)
    {
        foreach(int collideIndex in CollideIndex(ballSection[index], worldSection)
        {
            // worldSection[collideIndex] intersects ballSections[index]
            ...
            // something goes up here
        }
    }
    

    针对球、墙、砖调用您最喜欢的算法。

    别忘了给我发一份你的游戏!

    【讨论】:

      【解决方案2】:

      只是为答案添加另一个维度,这是一个经典的构建与购买决定:-) 如果您想构建,请务必自己动手。但是,如果您只想专注于您的游戏,那么您可以利用许多库来实现此功能:

      有一个非常好的其他引擎列表,可能比我在 XNA Wiki 上的 SO 答案中提供的更全面:
      http://www.xnawiki.com/index.php?title=Physics_Engine

      【讨论】:

        【解决方案3】:

        我会将桨分成不同宽度的矩形,例如:

        ABBCCCDDDDDDDDDDDDCCCBBA
        

        其中每个字母代表一个连续的矩形(DDDDDDDDD 是一个宽矩形)。既然你知道如何相交矩形,你可以说,为 D rect 设置反应将是完美反射(180-alpha),而对于 A、B、C 它将是(180 - alpha*factor),其中 factor取决于矩形,例如A 为 2,B 为 1.8,C 为 1.5。好吧,从技术上讲,对于 D 来说,因子是 1 :)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-01-04
          • 2020-04-26
          • 1970-01-01
          • 2011-03-01
          • 2016-07-20
          • 2017-09-24
          相关资源
          最近更新 更多