Circle1 (blue) is moving and its X and Y bounds are the screen (meaning it bounces off the walls).
Circle2 (black) is stationary. Circle1(blue) is supposed to bounce off of Circle2 without intersecting, regardless of the collision point. As you can see on the image below, the blue circle bounces off properly only at the blue arrow spots, otherwise(red arrows), blue ball goes INSIDE the black circle, gets stuck in there for a second and then gets out.
I have no idea why this is happening. Please take a look at my code and help me out. Thanks.
public void handle(ActionEvent t) {
if (counter++ % 5 == 0) {
// Moves the ball depending on the values of X and Y
circle.setLayoutX(circle.getLayoutX() + X); //velocity
circle.setLayoutY(circle.getLayoutY() + Y); //velocity
// Bounce off the walls (working perfectly)
final Bounds bounds = canvas.getBoundsInLocal();
boolean leftWall = circle.getLayoutX() <= (bounds.getMinX() + circle.getRadius());
boolean topWall = circle.getLayoutY() <= (bounds.getMinY() + circle.getRadius());
boolean rightWall = circle.getLayoutX() >= (bounds.getMaxX() - circle.getRadius());
boolean bottomWall = circle.getLayoutY() >= (bounds.getMaxY() - circle.getRadius());
//THE PROBLEM IS HERE
//Collision between circle1 and circle2 (stationary black circle.
double dx = circle.getLayoutX() - circle2.getLayoutX();
double dy = circle.getLayoutY() - circle2.getLayoutY();
double radii = circle.getRadius() + circle2.getRadius();
if ( (dx * dx) + (dy * dy) <= radii * radii) {
X = X * -1; //X gets inverted to change direction
}
//The code below is working perfectly.
// If the bottom or top wall has been touched, the ball reverses direction.
if (bottomWall || topWall) {
Y = Y * -1;
//circle.setLayoutY(circle.getLayoutY() - 50); - Wasn't working. Had to create X and Y to fix the problem.
}
// If the left or right wall has been touched, the ball reverses direction.
if (leftWall || rightWall) {
X = X * -1;
}
}
}
}));
loop.setCycleCount(Timeline.INDEFINITE);
loop.play();
}
P.S. Apologies for the amazing paint skills :D
X = X * -1;
\$\endgroup\$ – ThorinII Nov 20 '13 at 0:38normalize(cirlce1.center-circle2.center)
reflection is2*dot(surfNormal, velocity)*surfNormal-velocity
in vector math (see the formula for specular reflection) \$\endgroup\$ – ratchet freak Nov 20 '13 at 10:16