简体   繁体   中英

How to detect the collision of two drawn objects in c# 2010 express

I am trying to make a basic pong game using only drawn objects, so no picture boxes.

Here is my code: http://pastebin.com/pFNYa0HK

(I can pasted specific sections of the code if needed). What I need the code to do is detect the collision of the ball with the paddle and then reflect the ball off the paddle towards the other side of the game screen. pbCanvas is a picture box that covers the full form and is where all objects are drawn.

This is off the top of my head and written to test for collisions with the right paddle only:

There are three trivial possible collisions of a ball (at x,y with a radius r) with a paddle (Rectangle p):

  • Head on : bool CollisionFrontal = p.Contains(new Point(x+r, y));
  • Top : bool CollisionTop = p.Contains(new Point(x+r, y+r));
  • Bottom : bool CollisionBottom = p.Contains(new Point(x+r, yr));

And then there are the corners:

After creating a GraphicsPath for the ball

GraphicsPath  ballPath = new GraphicsPath();
ballPath.AddEllipse(p);

you can test for collisions with the two front corners of the paddle:

  • CornerTop : bool CollisionCornerTop = ballPath.IsVisible(p.Location);
  • CornerBot : bool CollisionCornerBot = ballPath.IsVisible(new Point(pX, p.Bottom));

You still will need to check for the right angle to reflect and try to keep track of the balls spin as well as combining the relative speeds in the case of non-frontal collisions

Without spin the direction is reflected on either the front or side lines or, when colliding with a corner from the tangent of the corner on the ball's circle.

And you will usually need to move the ball back to the exact collision point as the collision will often be detected 'too late'..

Note that all coordinates and other variables ought to be using floats! I didn't in the code above but you should..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM