Java 乒乓球在桨上滑动

标签 java collision-detection collision game-physics pong

我正在用java制作乒乓球游戏,我遇到了问题。

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

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

我的球类如下:

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

}

最佳答案

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

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

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

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

关于Java 乒乓球在桨上滑动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21238792/

相关文章:

java - 如何从此 API 中提取 "title"?

c++ - 圆和线段之间的错误碰撞检测

javascript - 与图像碰撞(不规则形状)

c - 如何处理静态链接库之间的符号冲突?

java - 如何在已选择的菜单项旁边添加复选标记?

java - 对一些明文进行两次编码并获得相同的哈希值

java - 当我对我之前在代码中执行过的同一 WebElement 执行 click() 时,出现空指针异常

algorithm - 圆圈碰撞

javascript - 如何防止角色在 Phaser 3 中使用 Matter Physics 在半空中跳跃?

c++ - Cocos2d-x collision hold back 一个节点