作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在用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/
编辑 2: Pastebin link to the full ball, bat, and AIbat classes. 编辑:我已经更新了 turbo 代码,只是对其进行了更好的评论。我也有一个链
我是一名优秀的程序员,十分优秀!