Reputation: 695
This is developed in JavaFX.
There are 2 balls - a dynamic ball and a stationary one. The first ball(dynamic) bounces off the walls and anything that comes in its way.
The second ball's purpose is to be an obstacle for the first ball. So, whenever the first ball touches the second ball, the first ball should instantly bounce away. Currently, the bouncing has very bad accuracy, and I don't know exactly how to fix it. Sometimes the first ball will bounce properly, but usually it will go INSIDE the second ball, get stuck in there for a moment, and then bounce away. The picture below goes over this exact issue.
Here's my code for detecting collision and responding to it:
//Pythagorean Theorem, to detect collision, by estimating the distance between the two circles
double dx = circle.getLayoutX() - circle2.getLayoutX();
double dy = circle.getLayoutY() - circle2.getLayoutY();
double radii = circle.getRadius() + circle2.getRadius();
double distance = (dx * dx) + (dy * dy);
double minDistance = radii * radii;
// I believe something is missing in the lines below, which is causing the problem.
if (distance < minDistance) { //If circle1(dynamic) collides with circle2(stationary)
c1SpeedX = c1SpeedX * -1; //Inverts direction.
}
I spent hours on google, but I was not able to find an answer. I hope somebody can provide a solution and explain the issue. Thanks a lot in advance everybody!
Upvotes: 0
Views: 981
Reputation: 825
Mmm...
I think you have some formulas errors.
By example, distance
and minDistance
should be
double distance = Math.sqrt((dx * dx) + (dy * dy));
double minDistance = radii;
Upvotes: 0
Reputation: 575
It's probably because the ball don't always have time to exit the bigger ball when its direction is reversed again and again.
If distance == minDistance:
Just do as you do now.
If distance < minDistance:
The ball is inside the larger one. Then it should already have bounced off and be a bit away. The ball should already have moved sqrt(distance-minDistance) away from the larger ball.
Upvotes: 1