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