home *** CD-ROM | disk | FTP | other *** search
Java Source | 2000-05-20 | 2.9 KB | 130 lines |
- /*
-
- Actor.java
-
- The Actor class controls the movement of an actor (ball) and playing
- sounds when it hits a wall.
-
- */
-
- import java.awt.*;
- import java.lang.*;
- import java.applet.*;
-
-
- public class Actor implements Runnable
- {
- private String name;
- private Color color;
-
- private Stage stage;
-
- private Thread runner;
-
- private double x0, y0; // Initial position in each dimension.
- private double v0x, v0y; // Initial velocity in each dimension.
- private double ax, ay; // Acceleration in each dimension.
- private double x, y; // Current position in each dimension.
-
- private double t;
- private final double dt = 0.05;
-
- private final int r = 10;
-
-
- public Actor(String n, Color c, Stage s)
- {
- name = n;
- color = c;
- stage = s;
-
- // Initial conditions.
- t = 0;
- x = x0 = 2*r; y = y0 = 2*r;
- v0x = 2; v0y = 0; // Velocity of 2 to the right.
- ax = 0; ay = 0.1; // Acceleration downward.
-
- runner = null;
- }
-
-
- // Methods for stage object to call.
-
- public void start()
- {
- if (runner == null) {
- runner = new Thread(this, name);
- runner.start();
- } else {
- runner.resume();
- }
- }
-
- public void stop() {
- runner.suspend();
- }
-
-
- // Methods for runner thread to run.
-
- public void run()
- {
- while (true) {
- int i;
- for (i=0; i<10; i++) {
- computeNewPosition();
- }
- try {
- Thread.sleep(5);
- } catch (InterruptedException e) {
- break;
- }
- }
- }
-
- public void paint(Graphics g)
- {
- int size = 2 * r;
- g.setColor(color);
- g.fillOval((int)(x - r), (int)(y - r), size, size);
- }
-
-
- // Private methods.
-
- private void computeNewPosition()
- {
- boolean collisionX, collisionY;
-
- // Update t and calculate one-dimensional motion with constant
- // acceleration in each dimension.
- t += dt;
- x = x0 + v0x*t + 0.5*ax*t*t;
- y = y0 + v0y*t + 0.5*ay*t*t;
-
- // Detect collisions with walls.
- collisionX = ((x - r) <= 0 || (x + r) >= stage.getSize().width);
- collisionY = ((y - r) <= 0 || (y + r) >= stage.getSize().height);
-
- if (collisionX || collisionY) {
- // A collision occurred, so set initial conditions to
- // current conditions and reset t. Reverse velocity in
- // any dimension in which a collision occurred.
- v0x = v0x + ax * t;
- v0y = v0y + ay * t;
- if (collisionX) v0x = -v0x;
- if (collisionY) v0y = -v0y;
- x0 = x;
- y0 = y;
- t = 0;
- gong();
- }
- }
-
- private void gong()
- {
- stage.gong();
- }
- }
-
-