This question already has an answer here:
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;
}
}
Firebase Cloud Functions: PubSub, "res.on is not a function"
TypeError: Cannot read properties of undefined (reading 'createMessageComponentCollector')
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
I am facing issue while expecting a setAttribute call from a mock
I am writing automation script for website and I am stucked with dropdownChecked with all available solutions but no use