0

我用java做一个乒乓球游戏,我遇到了一个问题。

错误在于,当乒乓球与 AI 或玩家的球拍相交时,球有时会发生多次碰撞。它基本上看起来就像球在桨上滑动。有时,球甚至会无限卡在桨后面。

有没有人遇到过这个错误或类似的东西?我对这种多重碰撞的东西感到困惑:(

我的球类如下:

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);
}

}

4

1 回答 1

5

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.

于 2014-01-20T16:16:50.707 回答