简体   繁体   English

Java-乒乓球拍和球碰撞的bug?

[英]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. 我正在打乒乓球,我将球x坐标设置为一旦击中桨便反转,并在未击中桨时停止。 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. 每当球接触球拍时, ballDeltax *= -1改变球的方向。

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. 您需要修改程序,以便当它改变方向时,它会在短时间内忽略代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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