I am making a game like pong except that there is only one paddle and the ball moves in projectile motion. The goal is to keep the ball bouncing on your paddle for as long as possible.
When the ball is hit by the paddle, the y
component of its velocity has it's sign flipped. The issue with this is that gravity also acts upon the ball, so when a ball is hit upwards it to speeds up due to the reversed effect of gravity.
This is the code for the ball class, including the tick
method which is called 60 times a second:
public Ball(double x, double y, Game game) {
super(x,y);
this.game=game;
}
public void tick() {
time+=1.0/60.0;
if(x<=0)
xreflection=1.0;
else if(x>=Game.Width-15)
xreflection=-1.0;
if(y<=0)
yreflection=1.0;
else if(y>=Game.Height-15)
gameover=1;//different variable here as I use this to end the game if the ball hits the bottom of the screen
x+=traj.xvel()*xreflection;
y-=traj.yvel(time)*yreflection;
if(Physics.Collision(this, game.getP())) {
time=2;
System.out.println("Collision");
yreflection=-1;
}
}
This is the ball Trajectory class which handles all the math:
public double xvel() {
double xvelo=initvel*Math.cos(Math.toRadians(theta));
return xvelo;
}
public double yvel(double time) {
double yvelo;
yvelo=initvel*Math.sin(Math.toRadians(theta))-(9.8*time);
return yvelo;
}
I have tried to use an if
statement with y
reflection to make 9.8 negative when y-reflection is 1 and positive when it is -1.