I was required to change the direction of a ball according to the collision between the ball and a rectangle.
That's my code:
public Velocity hit(Point collisionPoint, Velocity currentVelocity) {
Velocity newVelocity = currentVelocity;
// starting point - according to the upper left point of the rectangle
double startX = rectangle.getUpperLeft().getX();
double startY = rectangle.getUpperLeft().getY();
double x = collisionPoint.getX();
double y = collisionPoint.getY();
// Y direction
if ((x > startX) &&
(x < startX + rectangle.getWidth())) {
newVelocity.setDy((currentVelocity.getDy()) * (-1));
}
// X direction
else if ((y > startY) &&
(y < startY + rectangle.getWidth())) {
newVelocity.setDx(currentVelocity.getDx() * (-1));
}
// hits the corners
else {
newVelocity.setDx(currentVelocity.getDx() * (-1));
newVelocity.setDy(currentVelocity.getDy() * (-1));
}
return newVelocity;
}
Explanation: "hit" is a function that gets the collision point and the velocity of the ball. This function is called just in the case of a hit. In the function I checked if the ball hits the right and left walls of the rectangle, the bottom or tom or else - the corners.
public void moveOneStep() {
Velocity currentVelocity = this.getVelocity();
double collisionHeight;
double collisionWidth;
// starting point - according to surface
double collisionStartX;
double collisionStartY;
double x = this.center.getX();
double y = this.center.getY();
Line trajectory = new Line(new Point(x, y),
new Point(x + currentVelocity.getDx(),
y + currentVelocity.getDy()));
// get the closest collision point between the line and the rectangle
CollisionInfo collisionInfo = this.gameEnvironment.getClosestCollision(trajectory);
if (collisionInfo != null) {
// there's a collision
currentVelocity = collisionInfo.collisionObject().
hit(collisionInfo.collisionPoint(), currentVelocity);
} else {
collisionHeight = this.surface.getHeight();
collisionWidth = this.surface.getWidth();
collisionStartX = this.surface.getStartingPoint().getX();
collisionStartY = this.surface.getStartingPoint().getY();
// X direction
if ((x + currentVelocity.getDx() > collisionWidth -
radius - 1 + collisionStartX)
|| (x + currentVelocity.getDx() < radius + collisionStartX)) {
currentVelocity.setDx((currentVelocity.getDx()) * (-1));
}
// Y direction
if ((y + currentVelocity.getDy() > collisionHeight -
radius - 1 + collisionStartY) ||
(y + currentVelocity.getDy() < radius + collisionStartY)) {
currentVelocity.setDy(currentVelocity.getDy() * (-1));
}
}
this.setVelocity(currentVelocity);
this.center = this.velocity.applyToPoint(this.center);
}
Explanation: The ball moves according to a line. I check in each step if the line has a collision point with the rectangle.
I have a problem, the ball get inside the rectangle a little bit. How can I change that?
Thank you