I'm writing a game based on the breakout , but I can not think of a way to detect the collision between the corner of the ball area and the paddle, to be able to 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 a collision, it only reverses the vertical direction (y-axis).
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:
Onlywhentheballareacollideswiththepaddle'scorner,itcontinuesthetrajectoryofthex-axis,andtosimulatemorerealphysics,IwouldliketobeabletodetectwhenthecollisionoccursattheendsoftheobjectsandinvertthetrajectoryoftheXaxisoftheball.HowdoIdetectthis?Sincethereare4differentbigclasses,soasnottomessupthequestion,Iputafullyexecutableandcompleteexampleofthecodeinthe gist .