Java Pong ball glides on paddle

2019-09-18 15:50发布

im making a pong game in java, i've run into a problem.

The bug is that when the pong ball intersects with either the AI or player paddles, the ball will sometimes collide multiple times. It basically looks like like the ball is gliding on the paddle. Sometimes, the ball will even get stuck behind the paddle infinitely.

Had anyone ever encountered this error or something similar? I am confused with this multiple collision stuff :(

my ball class is below:

package ponggame;

import java.awt.*;

public class Ball{
int x;
int y;
int sentinel;

int width = 15;
int height = 15;

int defaultXSpeed = 1;
int defaultYSpeed = 1;

public Ball(int xCo, int yCo){
    x = xCo;
    y = yCo; 
}

public void tick(PongGame someGame) {
    x += defaultXSpeed;
    y+= defaultYSpeed;

    if(PongGame.ball.getBounds().intersects(PongGame.paddle.getBounds()) == true){
            defaultXSpeed *= -1;
    }
    if(PongGame.ball.getBounds().intersects(PongGame.ai.getBounds()) == true){
            defaultXSpeed *= -1;
    }
    if(PongGame.ball.y > 300){
        defaultYSpeed *= -1;
    }
    if(PongGame.ball.y < 0){
        defaultYSpeed *= -1;
    }
    if(PongGame.ball.x > 400){
        defaultXSpeed *= -1;
        PongGame.playerScore++;
        System.out.println("Player score: " + PongGame.playerScore);
    }
    if(PongGame.ball.x < 0){
        defaultXSpeed *= -1;
        PongGame.aiScore++;
        System.out.println("AI score: " + PongGame.aiScore);
    }

}

public void render(Graphics g ){
    g.setColor(Color.WHITE);
    g.fillOval(x, y, width, height);
}

public Rectangle getBounds(){
    return new Rectangle(PongGame.ball.x, PongGame.ball.y, PongGame.ball.width, PongGame.ball.height);
}

}

1条回答
Summer. ? 凉城
2楼-- · 2019-09-18 16:35

The problem is you're not changing the ball's position when it intersects the paddle, you're just reversing the x velocity.

So, if the ball intersects with a paddle deeply, x velocity is infinitely flipped between positive and negative.

Try tracking the ball's previous position on each tick. Upon collision, set the ball's position to its last position, and reverse x velocity.

This is a quick fix for your problems. A more realistic physics system would calculate the new position after collision more precisely, but this is good enough for low velocities, especially as you're not scaling by time.

查看更多
登录 后发表回答