0 java collision-detection collision game-physics pong
我在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);
}
Run Code Online (Sandbox Code Playgroud)
}
问题是当球与球拍相交时你没有改变球的位置,你只需要反转x速度.
因此,如果球与桨深交叉,则x速度在正负之间无限翻转.
尝试在每个刻度线上跟踪球的先前位置.碰撞时,将球的位置设置到最后位置,然后反转x速度.
这是您的问题的快速解决方案.更真实的物理系统会更准确地计算碰撞后的新位置,但这对于低速度来说已经足够了,特别是当你没有按时间缩放时.
| 归档时间: |
|
| 查看次数: |
2172 次 |
| 最近记录: |