【问题标题】:Java Pong ball glides on paddleJava Pong 球在桨上滑动
【发布时间】:2014-01-21 00:16:50
【问题描述】:

我正在用 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);
}

}

【问题讨论】:

    标签: java collision-detection collision game-physics pong


    【解决方案1】:

    问题是当球与球拍相交时,你并没有改变球的位置,你只是在反转 x 速度。

    因此,如果球与桨深相交,x 速度在正负之间无限翻转。

    尝试在每个刻度上跟踪球的先前位置。碰撞时,将球的位置设置为最后一个位置,并反转 x 速度。

    这是解决问题的快速方法。更真实的物理系统会更精确地计算碰撞后的新位置,但这对于低速来说已经足够了,尤其是当您没有按时间缩放时。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-12
      • 2021-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多