Download source: src2.zip
motion2.java
import java.awt.*; import java.awt.event.*; import java.util.*; import java.awt.geom.*; import javax.swing.Timer; import javax.swing.*; class TestPanel extends JPanel { Timer myTimer; int wait, wd, ht; Robot robot; WallSeg wallseg; ArrayList<Ball> pts = new ArrayList<Ball>(); double simtime = 0.0; TestPanel() { robot = new Robot(210,210,24,22,new Color(180,180,255)); Ball pt1 = new Ball(350, 250); pts.add(pt1); Ball pt2 = new Ball(250, 50); pts.add(pt2); Ball pt3 = new Ball(280, 190); pts.add(pt3); wallseg = new WallSeg(pt1,pt2); } public void update() { wd = getWidth(); ht = getHeight(); double tstep = 0.05; double tmin = 1.0; robot.updateVelocity(); double t = robot.intersect_window(wd,ht); if (t<tmin) tmin = t; t = wallseg.intersect(robot); for (Ball b: pts) { t = b.intersect(robot); if (t<tmin) tmin = t; } if (tmin<=tstep) { robot.move(tmin); robot.setVelocity(0,0); } else robot.move(tstep); simtime += tstep; repaint(); } /* Collision intersect_balls(Ball ball1, Ball ball2, double tstep) { // relative velocity double rx = ball2.vx - ball1.vx; double ry = ball2.vy - ball1.vy; // relative position double px = ball2.px - ball1.px; double py = ball2.py - ball1.py; // test radius double r = ball1.radius + ball2.radius - 1; double C = px*px + py*py - r*r; if (C<0) return null; // already intersecting double B = rx*px+ry*py; double A = rx*rx+ry*ry; if (A<=0.0) return null; // no relative velocity // quadratic At^2 + 2Bt + C = 0 double radical = B*B-A*C; if (radical<=0.0) return null; // no intersection (balls miss) double R = Math.sqrt(radical); double t; if (B>0) t = (-B + R)/A; else t = -(B+R)/A; if (t<=0.0 || t>tstep) return null; // no intersection within time limit return new Collision(t,ball1,ball2); } */ public void paintComponent(Graphics g) { super.paintComponent(g); robot.draw(g); g.setColor(Color.RED); int n; for (n=0; n<9; n++) { g.drawLine(10,10+n*50,410,10+n*50); g.drawLine(10+n*50,10,10+n*50,410); } for (Ball b: pts) b.draw(g); wallseg.draw(g); } public void startAnimation() { if (myTimer == null) { myTimer = new Timer(50,new TimerHandler() ); myTimer.start(); } else if (!myTimer.isRunning()) myTimer.restart(); } public void stopAnimation() { myTimer.stop(); } private class TimerHandler implements ActionListener { public void actionPerformed(ActionEvent actionevent) { update(); } } } public class motion2 { TestPanel panel; public void start() { panel.startAnimation(); } public void stop() { panel.stopAnimation(); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { TestPanel panel = new TestPanel(); JFrame frame = new JFrame("Robot Motion"); frame.add(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(440,460); frame.setVisible(true); panel.startAnimation(); } }); } }
Maintained by John Loomis, updated Thu Apr 09 10:22:05 2020