我正在用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/