11
I’m writing a game based on Breakout, but I can’t think of a way to detect the collision between the corner of the ball area and the paddle, so I can reverse the horizontal direction of the ball.
In my class Ball
, I have a method that takes care of the movement of the ball, and when it detects collision, it just reverses the vertical direction(axis y).
import java.awt.Graphics2D;
import java.awt.Rectangle;
public class Ball {
private int x = 0;
private int y = 15;
private final int DIAMETER = 30;
private int xSpeed = 1;
private int ySpeed = 1;
private Board board;
public Ball(Board board) {
this.board = board;
y = board.paddle.getTopY() - DIAMETER;
x = board.getPreferredSize().width / 2 - DIAMETER / 2;
}
public void move() {
if (x > board.getWidth() - DIAMETER || x < 0) {
xSpeed = -xSpeed;
}
if (y < 15) {
ySpeed = -ySpeed;
}
if (y > board.getHeight() - DIAMETER) {
board.gameOver();
}
//entre nesta if quando uma colisão é detectada
if (collision()) {
y = board.paddle.getTopY() - DIAMETER;
}
x += xSpeed;
y += ySpeed;
}
public void setSpeed(int speed) {
this.xSpeed = speed;
this.ySpeed = speed;
}
public void paint(Graphics2D g2) {
g2.fillOval(x, y, DIAMETER, DIAMETER);
}
public boolean collision() {
//detecta colisão entre a area da bola e o paddle
return board.paddle.getBounds().intersects(this.getBounds());
}
public Rectangle getBounds() {
return new Rectangle(x, y, DIAMETER, DIAMETER);
}
}
The result so far:
Only when the area of the ball collides with the corner of the paddle, it continues the trajectory of the x axis, and to simulate a more real physics, I would like to be able to detect when the collision occurs at the ends of the objects and reverse the trajectory of the x axis of the ball. How do I detect it?
As there are 4 different large classes, not to mess up the question, I put a fully executable and complete example of the code in gist.
Paddle is the area the ball walks?
– Jéf Bueno
@jbueno Paddle is the "horizontal bar" that the player controls on the sides to hit the ball.
– user28595
(x, y)
would be the left top point of the square circumscribed to the circle?– Woss
@jbueno x e y na classe ball seria isso: http://i.imgur.com/Oxobalm.jpg
– user28595