Trajectory.java

package com.bozoid.cis370.hw05;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.geom.*; // for Ellipse2D
import java.awt.font.*;
import java.util.Random;


/**
A <code>Trajectory</code> creates and manages a single point bouncing 
around in a rectangular area bounded by (0,0) at the low end and by a
variable pair of coordinates at the high end.  It randomly 
initializes its position and velocity from the supplied 
<code>Random</code> generator, with velocity components scaled to 
+/-<code>scale</code>.  Once the position and velocity are chosen, they
remain constant, except that (a) the velocity reverses when the 
<code>Trajectory</code> reaches the boundary and (b) the position will 
be adjusted to keep the <code>Trajectory</code> in bounds (e.g., when 
the frame width and/or height change).
*/
public class Trajectory
{
    public Trajectory(Random r,double scale,
        double framewidth,double frameheight)
    {
        vx = -scale + r.nextDouble()*2.0*scale;
        vy = -scale + r.nextDouble()*2.0*scale;
        x = r.nextDouble()*framewidth;
        y = r.nextDouble()*frameheight;
    }

    public Trajectory(Random r,int scale,
        int framewidth,int frameheight)
    {
        this(r,(double)scale,(double)framewidth,(double)frameheight);
    }

    public Point2D currentPoint() { return new Point2D.Double(x,y); }
    public double getX() { return x; }
    public double getY() { return y; }

    public Point2D nextPoint(int framewidth,int frameheight)
    {
        return nextPoint((double)framewidth,(double)frameheight);
    }

    public Point2D nextPoint(double framewidth,double frameheight)
    {
        x += vx;
        y += vy;
        if (x < 0.0)
            { x = 0.0;  vx = Math.abs(vx); }
        else if (x > framewidth)
            { x = framewidth;  vx = -Math.abs(vx); }
        if (y < 0.0)
            { y = 0.0;  vy = Math.abs(vy); }
        else if (y > frameheight)
            { y = frameheight;  vy = -Math.abs(vy); }
        return new Point2D.Double(x,y);
    }

    private double x,y,vx,vy;
}