0

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.

Gregg1989
  • 141
  • 2
  • 11
  • Anything unclear in the question? Please let me know, I really want to figure this out. – Gregg1989 Nov 25 '13 at 21:32
  • possible duplicate http://gamedev.stackexchange.com/questions/63421/ball-vs-45-degree-slope-collision-detection/63423#63423 – concept3d Nov 26 '13 at 05:19

1 Answers1

1

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.

Matthew
  • 29
  • 4
  • 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; } } – Gregg1989 Nov 26 '13 at 11:55
  • Is the same thing still happening, or something different? – Matthew Nov 28 '13 at 00:26