# How to find the point of intercept between two geometrical shapes in Java [duplicate]

348
July 04, 2017, at 03:43 AM

• Ball to Ball Collision - Detection and Handling 12 answers

I am working on making a simple game where I require the ball to move in a specific direction based on where the ball intercepts the other shape like Rectangle. The concept is similar to the classic Pong game. I've researched the web about this for quite a while but I'm unable to get a satisfactory answer.

I have found solutions where the direction of the ball's movement is decided by a random number generated by the Random class. But I would like to customise the movement based on the point of intersection between the two shapes, like move the ball upwards if it intersects the upper half of the rectangle.

Here's the random direction method I used as a preliminary implementation:

``````public void chooseRandomDirection() {
int random = new Random().nextInt(3);
switch (random){
case 0:
yVel=0;
break;
case 1:
yVel = 1;
break;
case 2:
yVel = -1;
break;
}
}
``````

Here's the entire Ball class in case your interested:

``````public class Ball extends Entity {
public Ball(Game game, float x, float y) {
super(game, x, y, 20, 20);
xVel = 1;
yVel = 1;
}
@Override
public void update() {
borderControl();
x += xVel;
y += yVel;
}
@Override
public void render(Graphics g) {
g.setColor(Color.WHITE);
g.fillOval((int)x,(int)y,width,height);
}
public void chooseRandomDirection() {
int random = new Random().nextInt(3);
switch (random){
case 0:
yVel=0;
break;
case 1:
yVel = 1;
break;
case 2:
yVel = -1;
break;
}
}
private void borderControl(){
if(y >= Game.HEIGHT-15)
yVel = -1;
if(y <= 0)
yVel = 1;
}
}
``````
POPULAR ONLINE

### Guice How to build a factory which depends on a parameter

I want to build a factory class using GuiceThe factory will take a parameter input based on which a particular service implementation would be instantiated

334

### Java algorithm in linked lists

I have the next classes: (Singly linked list)

950

### JMock matchers with setAttribute(String, Object)

I am facing issue while expecting a setAttribute call from a mock

316

### Select class in selenium webdriver is not working for dropdown

I am writing automation script for website and I am stucked with dropdownChecked with all available solutions but no use

366