问题
im making a pong game in java, i've run into a problem.
The bug is that when the pong ball intersects with either the AI or player paddles, the ball will sometimes collide multiple times. It basically looks like like the ball is gliding on the paddle. Sometimes, the ball will even get stuck behind the paddle infinitely.
Had anyone ever encountered this error or something similar? I am confused with this multiple collision stuff :(
my ball class is below:
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);
}
}
回答1:
The problem is you're not changing the ball's position when it intersects the paddle, you're just reversing the x velocity.
So, if the ball intersects with a paddle deeply, x velocity is infinitely flipped between positive and negative.
Try tracking the ball's previous position on each tick. Upon collision, set the ball's position to its last position, and reverse x velocity.
This is a quick fix for your problems. A more realistic physics system would calculate the new position after collision more precisely, but this is good enough for low velocities, especially as you're not scaling by time.
来源:https://stackoverflow.com/questions/21238792/java-pong-ball-glides-on-paddle