0
\$\begingroup\$

The blue ball is dynamic and is supposed to bounce off the walls, as well as the rectangle. Currently, the green rectangle is adding an invisible line to the scene, which doesn't let my ball go where I want it to. You can see the issue on the picture below and also see my source code.

enter image description here

Source code for dynamic circle vs. stationary rectangle collision:

public void collisionRect() {
                double dx = Math.abs(circle1.getLayoutX() - rect1.getLayoutX());
                double dy = Math.abs(circle1.getLayoutY() - rect1.getLayoutY());
                double rect1XRadius = rect1.getWidth() / 2;
                double rect1YRadius = rect1.getHeight() / 2;

                boolean xWalls = dx <= rect1XRadius;
                boolean yWalls = dy <= rect1YRadius;

                if (xWalls) { //if the ball hits any of the X walls
                    c1SpeedX = c1SpeedX * -1; //Invert direction of X
                }
                if (yWalls) { //if the ball hits any of the Y walls
                    c1SpeedY = c1SpeedY * -1; //Invert direction of Y
                }

            }

I don't understand where I've made a mistake and how I can make my code work. Source code examples will be greatly appreciated! Thanks.

\$\endgroup\$
1
\$\begingroup\$

In order for the collison with the rectangle to happen, the object must be both inside its bounds in the x and the y dimension. Try only reversing the velocity only if both xWalls and yWalls is true. To tell which side it collides with, just choose the smallest of dx and dy. If dx is smallest, it collided with the x sides, if dy is smallest it collided with the y sides.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ I'm afraid that's not working, or at least I didn't get it to. I added this if (xWalls && yWalls) { if (dx < dy) { c1SpeedX = c1SpeedX * -1; } if (dy < dx) { c1SpeedY = c1SpeedY * -1; } } \$\endgroup\$ – Gregg1989 Nov 26 '13 at 11:55
  • \$\begingroup\$ Is the same thing still happening, or something different? \$\endgroup\$ – Matthew Nov 28 '13 at 0:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.