Prev: A Simple Scripted Object Next: Textured Objects

3. Animated Objects

One of the most important features of scripted objects is that they can be "intelligent". Ordinary objects only define geometry, but scripted objects can define behavior as well.

This is demonstrated by the following script, which animates our cloud of spheres to make them fly around at random.


r = new Random(0);
t = script.getTime();
for (i = 0; i < 100; i++)
{
  pos = new Vec3();
  PerlinNoise.calcVector(pos, r.nextDouble()+t*r.nextDouble(), r.nextDouble()+t*r.nextDouble(), r.nextDouble()+t*r.nextDouble());
  script.addObject(new Sphere(0.05, 0.05, 0.05), new CoordinateSystem(pos, 0, 0, 0));
}

This script is almost identical to our previous one. There are only two differences. First, we call

t = script.getTime();

to determine the current time. This allows the object to animate itself by explicitly changing based on time. Second, we determine the position of each sphere with the following lines:


pos = new Vec3();
PerlinNoise.calcVector(pos, r.nextDouble()+t*r.nextDouble(), r.nextDouble()+t*r.nextDouble(), r.nextDouble()+t*r.nextDouble());

The PerlinNoise class (artofillusion.math.PerlinNoise) defines scalar and vector valued random noise functions. The calcVector() method maps a random vector to every point in space. For each sphere, we select a random starting location and a random direction by setting each component to r.nextDouble()+t*r.nextDouble(). As this position "moves" with time, the random vector generated by calcVector() changes smoothly. The result is a swarming mass of spheres. (There is another class called simply Noise that implements a different noise algorithm. In this case PerlinNoise produces a better looking result, but for most purposes Noise is the better choice.)

In this case, the script calculated the position of each sphere explicitly as a function of time. That is not always the most convenient approach. Suppose, for example, that you wanted a scripted object to "respond" to other events going on in your scene. You could always hardcode into your script the times at which the events occurred, but that would be very inconvenient. You really want to be able to keyframe the changes so they can easily be controlled through the score.

This is done by defining script parameters. Select "Edit Object..." on your scripted object, then press the "Parameters..." button. Click "Add" to add a new parameter, then enter "radius" for its name and "0.05" for its value. Click "OK".

Now enter the following script:

This produces the exact same cloud of spheres as our first script back in chapter 2. There is an important difference, however. If you add a Pose track to your scripted object, you can now keyframe the value of the radius parameter.

By using parameters to control different aspects of your scripted object, you can easily animate it in complex ways.

Prev: A Simple Scripted Object Next: Textured Objects