I'm attempting to bounce a ball in java, but I'm struggling to figure out how to reverse the vertical component of the ball's velocity when it hits the viewport. My main issue (which might be dumb) is that I don't understand how the velocity component's directions (- in this case) contribute to the overall velocity when the velocity formula squares the negative values. Thanks for the help.
Currently I sort of relaunch the projectile with an offset when it hits the viewport, but this has the issue of having the wrong angles.
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.Timer;
public class Trajectory5 extends JComponent {
private static final long serialVersionUID = 1L;
Timer timer; double x; double y; double vy; double vx;
double t = 0; double a = 70; double v = 40;
double offsetx = 0; double offsety = 400;
double xmult = 0;
public Trajectory5() {
setFocusable(true);
timer = new Timer(1, new TimerCallback());
timer.start();}
@Override
public void paintComponent(Graphics g) {
g.fillOval((int) x, (int) y, 10, 10);
}
protected class TimerCallback implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
t += .01;
x = ((int) v*Math.cos(Math.toRadians(a)) * t + offsetx) + -xmult;
y = getHeight() - ((int) v * Math.sin(Math.toRadians(a)) * t-.5 * 9.8 * (Math.pow(t, 2))) - offsety;
vy = v * Math.sin(Math.toRadians(a)) - (t * 9.8);
vx = v * Math.cos(Math.toRadians(a));
System.out.println(vy + " " + vx);
if (y > getHeight()) {
offsetx = x;
offsety = 0;
v = Math.sqrt(Math.pow(vx, 2)+Math.pow(vy, 2));
t = 0;
}
repaint();
}
}
public static void main(String[] args) {
JFrame frame = new JFrame(); frame.setSize(1000, 800);
Trajectory5 canvas = new Trajectory5();
frame.add(canvas); frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}