0

I've created a bouncing balls animation, that's drawn on a surface (library from my university) that has 2 frames in it, and 2 arrays of balls that half goes to the first frame and the second to the second frame. For some reason - the balls pass through to y and x axis of their frame. I've already tried doing some of the solutions that were suggested (like here) and it didn't help..

my code:

public static void updateBalVelocity(Ball ball, int width, int height,
                                     int minWidth, int minHeight) {
    //  get default value of the dx and dy
    double dx = ball.getVelocity().getDx();
    double dy = ball.getVelocity().getDy();

    //  check if the ball is touching the border (x/y axis) and if so -
    //  change it's directions
    if ((ball.getX() + ball.getSize() + dx) >= width) {
        dx = (dx > 0) ? -dx : dx;
    } else if ((ball.getX() - ball.getSize()) <= minWidth) {
        dx = Math.abs(dx);
    }

    if ((ball.getY() + ball.getSize() + dy) >= height) {
        dy = (dy > 0) ? -dy : dy;
    } else if ((ball.getY() - ball.getSize()) <= minHeight) {
        dy = Math.abs(dy);
    }

    //  apply the velocity to the ball
    ball.setVelocity(dx, dy);
}

 public static void moveBalls(Ball[] balls, DrawSurface d, int height,
                             int width, int minHeight, int minWidth) {
    for (Ball ball : balls) {
        updateBalVelocity(ball, width, height, minWidth, minHeight);
        ball.moveOneStep();
        d.setColor(ball.getColor());
        d.fillCircle(ball.getX(), ball.getY(), ball.getSize());
        ball.drawOn(d);
    }
}

and in the run method:

 while (true) {
        ...

        //  move balls
        BouncingBallHelper.moveBalls(ballsD1, d, 500, 500, 50, 50);
        BouncingBallHelper.moveBalls(ballsD2, d, 600, 600, 450, 450);
        gui.show(d);

        // wait for 50 milliseconds.
        sleeper.sleepFor(50);
    }
2
  • Have you tried debugging and step through when it touches the border?
    – Locked
    Mar 13, 2019 at 20:13
  • I have, and it shows that it's being updated correctly.. I have no idea what goes wrong
    – Elad G
    Mar 13, 2019 at 20:31

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.