Java Reference

In-Depth Information

var deltaX;//change in x location per step

var deltaY;//change in y location per step

init{

//radius = 5;

fill = Color.RED;

//radom direction in radians

var theta = random.nextFloat()*2.0*Math.PI;

deltaX = Math.cos(theta)*speed;

deltaY = Math.sin(theta)*speed;

}

package function doStep(){

//remove particle if particle has expired

if (--initialSteps == 0){

delete this from (parent as Group).content;

}

//advance particle's location

translateX += deltaX;

translateY += deltaY;

}

}

The
Particle
class has changed only slightly: the attribute
duration
is now public and a new

attribute called
speed
was added. The attribute
speed
is used in the
init
method to calculate
deltaX
and

deltaY
. The rest of class is unchanged.

It is worth looking at how
deltaX
and
deltaY
are calculated. A random angle is generated that

represents the direction the
Particle
will travel, and this angle is used to calculate
deltaX
and
deltaY
.

The following code shows how this is implemented.

var theta = random.nextFloat()*2.0*Math.PI;

deltaX = Math.cos(theta)*speed;

deltaY = Math.sin(theta)*speed;

The change in
X per step
(
deltaX
) is simply the
cosine
of the angle
theta
multiplied by
speed
. The

change in
Y per step
(
deltaY
) is the
sine
of the angle
theta
, multiplied by
speed
. The diagram in Figure 2-4

shows these relationships.