Slateboard
Slateboard

Reputation: 1031

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.

Upvotes: 1

Views: 792

Answers (3)

Joel Martinez
Joel Martinez

Reputation: 47749

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:

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

Upvotes: 1

Schultz9999
Schultz9999

Reputation: 8926

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 :)

Upvotes: 0

Default Writer
Default Writer

Reputation: 2566

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!

Upvotes: 4

Related Questions