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

問題は、ボールがパドルと交差するときにボールの位置を変更していないことです。x 速度を逆にしているだけです。

したがって、ボールがパドルと深く交差すると、x 速度は正と負の間で無限に反転します。

各ティックでボールの前の位置を追跡してみてください。衝突時に、ボールの位置を最後の位置に設定し、x 速度を逆にします。

これは、問題の迅速な修正です。より現実的な物理システムは、衝突後の新しい位置をより正確に計算しますが、特に時間でスケーリングしていないため、速度が遅い場合はこれで十分です。

于 2014-01-20T16:16:50.707 に答える