private void CheckCollisions(MovingBall ball) { // Make list of balls to check collisions against List <MovingBall> collisionList = new List <MovingBall>(); foreach (ColourPoolBall b in balls) { collisionList.Add(b); } // Remove ball as we don't need to see if ball collides with itself collisionList.Remove(ball); // Check for collision with every other ball foreach (ColourPoolBall b2 in collisionList) { if (ball.CollidesWith(b2)) { ball.Touching(b2); //bounce both balls - this is not very accurate :-( ball.XSpeed *= -1; ball.YSpeed *= -1; b2.XSpeed *= -1; b2.YSpeed *= -1; } } }
public bool CollidesWith(MovingBall anotherBall) { // Get differences of coords int dx = xCoord - anotherBall.xCoord; int dy = yCoord - anotherBall.yCoord; // Euclidean Distance between the balls double dist = Math.Sqrt((double)(dx * dx) + (double)(dy * dy)); // If distance is less than the diameter, the balls are touching return(dist < (double)size); }
public void Bounce(MovingBall anotherBall) { // Get differences of coords int dx = xCoord - anotherBall.xCoord; int dy = yCoord - anotherBall.yCoord; //bounce both balls - this is not very accurate :-( XSpeed *= -1; YSpeed *= -1; anotherBall.XSpeed *= -1; anotherBall.YSpeed *= -1; }
private bool CheckOverlaps(MovingBall ball) { //check if overlaps any existing balls foreach (ColourPoolBall b in balls) { if (ball.CollidesWith(b)) { ball.Touching(b); return(true); //found an overlap } } return(false); //got to end of loop, so no overlaps }
public void Touching(MovingBall anotherBall) { while (CollidesWith(anotherBall)) { if (X < anotherBall.X) { MoveHorizontal(-1); } else { MoveHorizontal(+1); } if (Y < anotherBall.Y) { MoveVertical(-1); } else { MoveVertical(+1); } } }