开发者

What's the easiest way to implement collision detection in an XNA Game w/ C#?

开发者_开发百科

I'm basically working on a Pong clone, and I wanted to add collision. The way I wanted it to work, is that the paddles would each be divided into 4 sections (not visually), and the ball will react differently depending on which section it hits.

As far as collision goes, I only know rectangle collision, and that's basically the entire paddle as a whole. I do not know how to make it so the paddle has 4 possible points of collision with different reactions.


Just break paddle into 4 pieces, and keep it as one piece :)

Collide method returns -1 if rects do not collide, or a first index of collision.

CollideIndex method returns IEnumerable indexes of collided rects. ;)

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
    }
}

Call your favorite algorithm against balls, walls, bricks.

Do not forget to send me a copy of your game!


Just to add another dimension to the answers, this is a classic build vs buy decision :-) If you want to build, by all means do it yourself. However if you would rather just focus on your game, there are plenty of libraries out there that you could leverage for this functionality:

  • Farseer Physics (http://farseerphysics.codeplex.com/), focused on 2D, perfect IMO for what you describe above
  • Physics2D (http://sites.google.com/site/physics2d/)
  • JigLibX (http://jiglibx.codeplex.com/)

There's a really good list of other engines which will likely be more comprehensive than what I could provide in an SO answer on XNA Wiki:
http://www.xnawiki.com/index.php?title=Physics_Engine


I'd divide the paddle into rects of different width, e.g.:

ABBCCCDDDDDDDDDDDDCCCBBA

where each letter represents a continuous rect (DDDDDDDDD is one wide rect). Since you know how to intersect rects, you can, say, set for D rect the reaction will be perfect reflection (180-alpha), where as for A,B,C it will be (180 - alpha*factor), where factor depends on the rect, e.g. for A it's 2, for B 1.8, for C 1.5. Well, technically for D the factor is 1 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜