简体   繁体   中英

Java - Pong paddle and ball collision bug?

I'm making pong and I have set the balls x cordinate to reverse as soon as it hits the paddle and stop when it doesnt hit the paddle. this code works "most" of the time, but "sometimes" the ball just stops as soon as it hits the paddle for no apparent reason. any tips or hints i could get for this. ps i couldn't find anyone with the same problem

heres the code segment:

        //ball bounces on p1's paddle
    if(nextBallLeft < p1RightSide){
        if(ballY > p1Y && ballY < getHeight() - p1Y + paddleHeight){
             ballDeltaX *= -1;
        }
        else{
            System.out.println("1");
            ballDeltaX = 0;
            ballDeltaY= 0;

        }

There's a case where your ball will "enter" the paddle, and the collision will make it reverse. In the next loop, while it's still inside the paddle, it will reverse again. This pattern goes on forever and your ball will get stuck.

To solve this you need to 'trace' the ball path and detect collision before hitting the wall. This way you can make the next step of the ball be the necessary amount to reach the surface of your paddle.

ballDeltax *= -1 changes the direction of the ball, whenever the ball touches the paddle.

However, what may happen is that when the ball touches the paddle, it changes direction, but since it is still touching the paddle, it changes direction again thereby creating an infinite loop.

You need to modify the program so that when it changes direction, it ignores the code for a short period of time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM