Quantcast
Channel: Ball to Ball Collision - Detection and Handling - Stack Overflow
Viewing all articles
Browse latest Browse all 16

Answer by FlySwat for Ball to Ball Collision - Detection and Handling

$
0
0

You have two easy ways to do this. Jay has covered the accurate way of checking from the center of the ball.

The easier way is to use a rectangle bounding box, set the size of your box to be 80% the size of the ball, and you'll simulate collision pretty well.

Add a method to your ball class:

public Rectangle getBoundingRect(){   int ballHeight = (int)Ball.Height * 0.80f;   int ballWidth = (int)Ball.Width * 0.80f;   int x = Ball.X - ballWidth / 2;   int y = Ball.Y - ballHeight / 2;   return new Rectangle(x,y,ballHeight,ballWidth);}

Then, in your loop:

// Checks every ball against every other ball. // For best results, split it into quadrants like Ryan suggested. // I didn't do that for simplicity here.for (int i = 0; i < balls.count; i++){    Rectangle r1 = balls[i].getBoundingRect();    for (int k = 0; k < balls.count; k++)    {        if (balls[i] != balls[k])        {            Rectangle r2 = balls[k].getBoundingRect();            if (r1.Intersects(r2))            {                 // balls[i] collided with balls[k]            }        }    }}

Viewing all articles
Browse latest Browse all 16

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>