BallCollisionProgram
Retired DISLab
BallCollisionProgram.java
import acm.graphics.*; import acm.util.*; import java.awt.event.*; import java.util.*; public class BallCollisionProgram extends RandomBalls { @Override public void run() { ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { moveOneStep(); } }; SwingTimer timer = new SwingTimer(TIMER_RATE, listener); timer.start(); } @Override public void mouseMoved(MouseEvent e) { // nothing } @Override public void moveObjects() { super.moveObjects(); ArrayList<GObject> removedObjs = new ArrayList<GObject>(); Iterator<GObject> it = iterator(); while (it.hasNext()) { Iterator<GObject> it2 = iterator(); GBall gobj = (GBall)it.next(); while (it2.hasNext()) { GBall target = (GBall)it2.next(); if (target == gobj) continue; // collision check double distance = GMath.distance(gobj.getX(), gobj.getY(), target.getX(), target.getY()); if (distance - (gobj.getRadius() + target.getRadius()) <= 0.00001) { // collision if (gobj.getRadius() < target.getRadius()) { target.setRadius(target.getRadius() - gobj.getRadius()); removedObjs.add(gobj); } else if (gobj.getRadius() > target.getRadius()) { gobj.setRadius(gobj.getRadius() - target.getRadius()); removedObjs.add(target); } else { removedObjs.add(gobj); removedObjs.add(target); } System.out.println("BOOM"); } } } for (int i = 0; i < removedObjs.size(); i++) { remove(removedObjs.get(i)); } } public static void main(String[] arg) { new BallCollisionProgram().start(); } private static final int TIMER_RATE = 20; public static final long serialVersionUID = 1; }
GBall.java
/* * File: GBall.java * ---------------- * This file defines a GObject class that represents a ball. */ import acm.graphics.*; /** * This class defines a GCompound subclass that represents a ball * whose reference point is the center rather than the upper * left corner. */ public class GBall extends GCompound { /** Creates a new ball with radius r centered at the origin */ public GBall(double r) { radius = r; ball = new GOval(2 * radius, 2 * radius); ball.setFilled(true); add(ball, -radius, -radius); markAsComplete(); } /** Creates a new ball with radius r centered at (x, y) */ public GBall(double r, double x, double y) { this(r); setLocation(x, y); } public void setRadius(double r) { ball.setSize(r * 2, r * 2); } public double getRadius() { return radius; } /* public void setSize(double r) { ball.setSize(r, r); } public double getWidth() { return ball.getWidth(); } public double getHeight() { return ball.getHeight(); } */ private GOval ball; private double radius; }