简体   繁体   中英

Collision detection in game of pong corner cases causing issues

I have made a game of pong and everything about it is working so far. I did the collisions against the paddles to the ball and it can correctly bounce them away unless it hits the corners.

This is a video of what happens when the ball hits the corner of one of the paddles.

https://drive.google.com/file/d/1nyRzsp5tn5Qvst7kVjtlr_rDNH98avbA/view?usp=sharing

Essentially what you can see happen in the video is the ball hits the the paddle on the left at the corner and it doesn't bounce back it just traverses the paddle downwards and then keeps going and they get a point. Here is my code for the collision testing

public void collision() {
    this.width = (float) getBounds().width;
    this.height = (float) getBounds().height;
    for (int i = 0; i < handler.objects.size(); i++) {
        if (handler.objects.get(i).getId() == ID.ball) {
            GameObject current = handler.objects.get(i);
            if (getBounds().intersects(current.getBounds())) {
                current.setVx(current.getVx() * -1);
            }

        }
    }
}

getBounds is an overridden method that just returns a rectangle for both the ball(which is a circle) and the paddle

I am happy to provide more of my code if necessary.

Any help on this would be great, thanks!

You are swapping the velocity direction each time you are hitting the paddle, even when you are still touching the paddle in the next frame. The solution is to swap the velocity direction only when the ball is heading towards the paddle, not when (already) going away. The pseudo code can look like this:

if (GeometryUtil.isDirectionGoingDown(direction)) {
    if (GeometryUtil.isBallHittingHorizontalLine(
            newPosition,
            Ball.RADIUS,
            paddleTopLeft,
            paddleTopRight)) {
        direction = calculateNewDirectionAfterHittingPaddle(
                        direction,
                        paddlePosition,
                        newPosition);
        ball.setDirection(direction);
    }
}

Here the GeometryUtil.isDirectionGoingDown() method is checking if the ball is actually going down. That way the new direction is only set when this condition returned true . When the direction has been swapped in one frame, the next frame will not swap the direction again because GeometryUtil.isDirectionGoingDown() will return false then.

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