Physlet Tutorial

(Excerpt from Teaching with Physlets by Wolfgang Christian and Mario Belloni.)

The goal of this tutorial is to give the reader an idea of how to script an applet in Animator version 4 from the ground up. Many of the methods and techniques that are found in this chapter regarding Animator will also appear in other Physlets.

 

Figure 1: Pendulum in a truck scripted with the Animator Physlet.

 

Animator provides an environment for the student to see real-time animations of physical (and non-physical) situations. Students view these animations and make time, position, velocity, acceleration, and force measurements in order to answer questions about the motion of objects that appear in the Physlet. Because of its versitility, Animator is probably the most robust and widely used Physlet currently available. Applets ranging in content from kinematics to particle physics have been created to better help students to visualize physical situations.

The description "Animator" refers to the current version, Animator4. For early adopters of Physlets who have scripted previous versions of Animator, there are some new and interesting features in the latest version and you should script using this version.[1]  There are also a few backward compatibility issues (orphaned methods and new methods) in updating old Animator scripts to the new Animator that are described in the reference section. Scripts using version 3 of Animator will still run, but they are no longer supported. Scripts using version 1 and 2 may not run if they use orphaned methods.  If you have never scripted before, the knowledge of the existence of these old scripts is important if you obtain scripts from others.

The goal of this chapter is to give the reader an idea of how to script an applet in Animator version 4 from the ground up. Many of the methods and techniques that are found in this chapter regarding Animator will also appear in other Physlets.

 

An Animator Template

OK, so a red ball on a screen does not sound that exciting. However, once a script is written to have the ball appear on a browser, getting it to move is not too difficult. An html page will deliver the Animator applet across the Internet and be readable by a web browser. The html code:

 

<html>

<head>

<title>Projectile</title>

</head>

<body bgcolor="#FFFFFF">

</body>

</html>

creates a web page entitled Projectile that is completely blank and has a white background (<body bgcolor="#FFFFFF">). In any text editor the SAVE AS… projectile.html command creates the actual web page locally on your computer. A script must now be written that will place a red ball in an applet. Insert the following few lines of JavaScript into the head of the web page, that is, between the <head> and </head> tags.

 

<script language="JavaScript">

function proj1_0(){

document.animator.setAutoRefresh(false);

document.animator.setDefault();    

document.animator.setPixPerUnit(5);

document.animator.setGridUnit(2);

id1=document.animator.addObject("circle","x=0, y=0,r=10");

document.animator.setRGB(id1, 255,0,0);

document.animator.setTimeInterval(0,6);

document.animator.setAutoRefresh(true);

document.animator.forward();

}

</script>

Script 1: Adding a circle to the animator Physlet.

 

 

This script defines a function, proj1_0(), that will animate a red ball. Note the syntax within the code. Java uses "dot" syntax which is common in object oriented programming.  Invoking a method of an applet that has been embedded into a document begins by specifying a reference to the embedded object: document.animator.  Following the object reference is the method to be performed the Animator Physlet. This script uses 8 methods.  One method is used twice with different arguments.

 

·       setAutoRefresh(false); //turns off the automatic drawing of the applet.

·       setDefault(); //clears the Physlet and sets default parameters.     

·       setPixPerUnit(5); //sets the pixels per unit on the animation.

·       setGridUnit(2); //sets the background grid unit for the animation. A value of zero turns off the background grid.

·       id1=addObject("circle","x=0, y=0, r=10"); //adds a circle to the animation at the coordinate (x,y) which in our case is at the origin.  The addObject method returns a unique integer identifier that can be used to identify the object.

·       setRGB(id1,255,0,0); //sets the color of the object with the given id. Here it makes our red ball red. Specifically, the argument of the command is in the form (id,R,G,B) where R(ed),G(reen), and B(lue) are integers ranging from 0 to 255.

·       setTimeInterval(0,6); //sets the time interval. Here the time interval of the animation is set to run 0<t<6. Note that the time interval is internal to the applet and may not represent the real time interval that the applet animates. There is another method of interest that stops an animation. It is setOneShot(0,6,"End of Animation"); which stops the animation and displays a message when the applet stops running.

·       setAutoRefresh(false); //turns on the automatic drawing of the applet.

·       forward(); //makes the animation run.

 

 

The double slash, //, is a shorthand that is used in many programming languages to insert a short comment.  It signifies to the JavaScript compiler that the remainder of the line is text and should not be interpreted as code.  

 

The web browser must now be told where to find the Physlet class, how many pixels the applet should occupy in the html page, and what initial parameters should be used. This is accomplished by adding the following to the body of the html page:

 

<h3 align="left">Projectile Motion</h3>

<p align="center">

 <applet codebase="../classes/" code="animator4.Animator.class"

archive="Animator4_.jar,STools4.jar"

align="baseline" width="350" height="200" id="animator" name="animator">

<param name="FPS" value="10">

<param name="dt" value="0.1">

<param name="showControls" value="false">

</applet>

</p>

 

This markup does three things. The code in between the <applet> </applet> tag reserves a portion of the web page for the applet that will have a heading "Projectile Motion", will be centered, and will have a size of 350 by 200 pixels. The remainder of the code tells the web browser where to find the Animator.class file. In this example, it resides in a subdirectory named classes. The dot-dot notation is again shorthand for locating this subdirectory.  Dot-dot refers to the parent directory of the current directory.  So dot-dot followed by another dot-dot would tell the browser to move up two directories before looking for the classes subdirectory.  Also the keywords “id” and “name” give the Java document a name as read by Internet Explorer and Netscape Navigator/Communicator, respectively (both are included for backward compatibility).  Note that this is the exact same document name/id that appeared in the script above, in this example: animator. In order for the applet to run properly these names must be exactly the same. Also noteworthy, the World Wide Web Consortium, W3C, has recommended that vendors adopt the keyword “object” to replace both the modifiers "id" and "name".  Expect to see this standard adopted in the next browser release.

 

As these applets will vary in complexity and appear on a variety of different computers, all with different processor speeds, the rate at which the screen redraws and the animation time step should be taken into account. This is done by adding the following parameters to the animation right above the end applet </applet> line. The Frames Per Second (FPS) parameter controls how often a new image will be calculated and displayed on the screen.  Too small a value produces image flicker and too large a value causes jerky motion due to the microprocessor not being able to perform the calculations quickly enough. The parameter dt, defines the time step for each animation frame. If FPS is set to 10 and dt is set to 0.1, the animation will proceed in real time without noticeable flicker on most microcomputers.  Setting the showControls parameter to false hides the user interface thereby allowing the author to add a custom one using html form elements at a later time.

 

The html page is finished with the addition of a hyperlink to the function defined in the head that will start the animation when the reader of the page clicks on it:

 

<a href="JavaScript:proj1_0()"> Start</a>

 

If all went well the following applet should appear on your web browser:

 

 

Figure 2: Stationary red ball on screen.

 

When the applet is started by clicking the Start hyperlink, the time in the upper left hand corner of the applet will cycle from 0-6 seconds, and the ball will remain stationary.

 

Simple Motion

 

We are now in a position to make the animation more interesting. To do so, the position of the red ball must vary with animation time t. If the following line is added after the addObject method of the script 3

 

document.animator.setTrajectory(id1,"(8.55*t)", "(23.49*t-4.9*t*t)");

 

the ball will move across the screen along the x(t)  and y(t)  trajectory specified by the second and third arguments, respectively, of the setTrajectory method. The particular values above give an initial velocity (in both the x- and y-directions) and the correct acceleration due to gravity (acting solely in the y-direction).

 

There are now several problems to be addressed. The animation starts at t=0 with the ball appearing on the screen and then moving off screen. For pedagogic reasons the ball should be a little more centered in the applet, appearing in the bottom left corner and disappearing in the bottom right corner some time later. For objects that were in motion at t=0, starting the object off screen allows students to view the motion as intended. Otherwise, the motion appears to begin as soon as the Start button is pressed. This is accomplished by adding the following line to our script directly below the setGridPix line:

 

document.animator.shiftPixOrigin(-100,-100);

 

The method shiftPixOrigin will shift the origin of coordinates down and to the left by 100 pixels in each direction, which is exactly what is needed for the animation of the ball to be centered on the applet grid. There is yet another problem: How is the user supposed to control the applet? Assuming that we will be asking the user to measure something pertaining to the animation, how does he/she do that without starting and stopping the animation? To add this functionality, standard html form buttons are used to create VCR-type controls beneath the animation grid.  It is easiest to add these buttons using a WYSIWYG authoring tool but you they can also be created by adding the following lines of html to the page following the end applet tag, </applet>.[2]

 

<form>

<input type="button" value="play"

onclick="document.animator.forward()">

<input type="button" value="pause"

onclick="document.animator.pause()">

<input type="button" value="&lt;&lt;step"

onclick="document.animator.stepBack()">

<input type="button" value="step&gt;&gt;"

onclick="document.animator.stepForward()">

<input type="button" value="reset"

onclick="document.animator.reset()">

</form>

 

Note again that the document name appearing in the above html is (and must be) exactly the same as what appeared in the applet tag (id/name) and in the script itself, again for this example: animator. This is what now appears on our browser:

 

 

Figure 3: Ball on screen with controls.

 

with the red ball appearing in the lower left of the applet and follows a parabolic path before disappearing on the lower right of the applet. The complete html page is as follows:


<html>

<head>

<script language="JavaScript">

function proj1_0(){

      document.animator.setAutoRefresh(false);

      document.animator.setDefault();    

      document.animator.shiftPixOrigin(-100,-100);

      document.animator.setPixPerUnit(5);

      document.animator.setGridUnit(2);

id1=document.animator.addObject("circle", "r=10");

document.animator.setTrajectory(id1,"(8.55*t)","(23.5*t-4.9*t*t)");

      document.animator.setRGB(id1, 255,0,0);

      document.animator.setTimeInterval(0,6);

      document.animator.setAutoRefresh(true);

      document.animator.forward();

}

</script>

<title>Projectile</title>

</head>

 

<body bgcolor="#FFFFFF">

<h3 align="left">Projectile Motion</h3>

<p align="center">

<applet codebase="../classes/" archive="Animator4_.jar,STools4.jar"

code="animator4.Animator.class"

align="baseline" width="350" height="200" id="animator" name="animator">

<param name="FPS" value="10">

<param name="dt" value="0.1">

<param name="showControls" value="false">

</applet>

</p>

<form>

<p><input type="button" value="play" onclick="document.animator.forward()">

<input type="button" value="pause" onclick="document.animator.pause()">

<input type="button" value="&lt;&lt;step" onclick="document.animator.stepBack()">

<input type="button" value="step&gt;&gt;" onclick="document.animator.stepForward()"> <input type="button"

   value="reset" onclick="document.animator.reset()"></p>

</form>

<a href="JavaScript:proj1_0()">Start</a></p>

 

</body>

</html>

Script 4 Projectile motion scripted using Animator.

Projectile

The basic projectile motion applet will be improved with the addition of a few lines of script. These additions will address questions the script author might want to ask students regarding projectile motion. Text for a standard question [Giancoli Physics, p. 70]: "A projectile has the least speed at what point in its path?" can be easily embedded below the html buttons using standard tags.

 

<h3>Question 1</h3>

<p>A projectile is shown in the above animation (position is given in meters and time is in seconds). A projectile has the least speed at what point in its path?</p>

 

In writing the text for these types of problems, the author should be careful to stress units. The applet itself is unitless, since the grid spacing can represent any spatial length. The same is true of the time display. A simple addition to the text of the problem such as "position is given in meters and time is in seconds" is usually sufficient to stress the importance of units.[3]

 

The current applet correctly depicts projectile motion, but perhaps not in the correct form for most students to visualize the answer to the above question (and subsequent questions). Two successive additions to the script will help students answer this question correctly (and in the process hopefully better understand projectile motion). First, add the line:

 

document.animator.setTrail(id1,150);

 

below the setRGB line. (What is crucial in the line placement is that the id must have already been instantiated. Hence, any line after the addObject line will suffice.) This addition turns on the trail to the object in question, namely id1, the red ball. This will leave a parabolic curve on the screen where the ball has traveled during the last 150 time steps, an effective visual aid to answer the question posed above. Note that the trail will inherit the color of the original object; in this example the trail is red.

 

Depending on the questions asked of the student, footprints marking where the ball has traveled may make a better visual aid than the solid trajectory line. Since these footprints will be evenly spaced in time, this technique gives students a visual aid when looking at constant velocity or constant acceleration animations. To add these footprints, add the following two lines beneath the setTrail line:

 

document.animator.setFootPrints(id1,5);

document.animator.setGhost(id1,true);

 

The argument of the setFootPrints method places a marker where object id1 appears at an interval of 5 time steps (the dt parameter that set in the <applet> tag). If instead we had setFootPrints(id1,1) the footprints  would be left after every  time step.  There are other ways to mark the path of an object.   The Ghost feature in the second line of script above paints a pale ghost image of the object on screen with the same frequency as the FootPrints. This is exactly the effect depicted in Figure 2. As with the Trail and FootPrints, the Ghosts inherit the color of the object in question.

 

This applet's flexibility can be further exploited by asking different questions regarding the motion of the red ball such as:

 

·         What is the red ball's horizontal speed?

·         What is the red ball's velocity at the top of its motion?

·         What is the red ball's vertical acceleration?

 

Students often see projectile motion and automatically respond that all accelerations are 9.8 m/s2.  To counter this tendency, state in the problem that the motion is, say, on the moon, and then change the acceleration in the animation to match this assertion. Do so by changing the line:

 

document.animator.setTrajectory(id1,"(8.55*t)", "(23.49*t-4.9*t*t)");

to

document.animator.setTrajectory(id1,"(8.55*t)", "(23.49*t-0.816*t*t)");

since the acceleration due to gravity on the moon is about one sixth of the acceleration due to gravity on the earth. This points out one key feature of these animations. The author manipulates the JavaScript to make the situation depicted in the animation physical. Hence, the author may also make the animation non-physical to test student understanding of the material.

 

Again, since the applet itself is unitless, the author should be careful to stress units since the grid spacing can represent any spatial length.

 

Red Ball Revisited, Again!

With a few more modifications to the script, the applet can again be augmented to include velocity vectors. First  comment off the setFootPrints and setGhost lines using the double slash at the beginning of the lines:

 

//document.animator.setFootPrints(id1,1);

//document.animator.setGhost(id1,true);

 

since we want the solid red trail to again follow the red ball. Should we want these two lines back in the script, simply remove the double slashes. Consider the following additions to the applet below the document.animator.setTrail(id1,150) line:

 

id2=document.animator.addObject("arrow", "h=0,v=23.5-9.8*t");

document.animator.setAnimationSlave(id1,id2);

id3=document.animator.addObject("arrow", "h=8.55,v=0");

document.animator.setAnimationSlave(id1,id3);

id4=document.animator.addObject("arrow", "h=8.55,v=23.5-9.8*t ");

document.animator.setAnimationSlave(id1,id4);

document.animator.setRGB(id4, 14,49,188);

 

 

There are now three new objects that follow the red ball around the screen. This addition to the script places black arrows corresponding to the ball's velocity in the x- and y- directions and a pale blue arrow representing its total velocity, all placed with their tails at the center of the ball as shown below:

 

 

Figure 4: Projectile motion applet with velocity arrows.

To avoid student confusion regarding the arrows and what they mean, in the text of the problem, state that the black arrows represent the velocity components and the blue arrow represents the total velocity vector.

Adding Text to the Red Ball Animation

Two more optional features will finish off this example. Sometimes it is helpful to give students a continuous display of coordinates instead of having students mouse-down to read coordinates. A caption or text also can also be added in cases where information for students is best given in the applet itself as opposed to in the text of the problem. In this case add the following lines of code to the existing script beneath the setTrail line:

 

document.animator.setShowCoordinates(id1,true);

document.animator.setCoordinateOffset(id1,-35,0);

document.animator.setObjectFont(id1,"Hevetica",1,12);

capid=document.animator.setObject("caption", "My First Physlet");

document.animator.setShowCoordinates(capid,true);

document.animator.setCoordinateOffset(capid,0,6);

document.animator.setObjectFont(capid,"Hevetica",1,16);

 

These additions draw the x-y coordinates of id1, again the red ball, offset to the left so as not to be right on top of the ball. The coordinates are drawn with the font Hevetica bold in 12pt. The second argument of setFont, 1, bolds the font in question (0 draws the default font,2 draws the italic font, and 3 draws the bold, italic font). Also added is a caption, "My First Physlet", in Hevetica bold 16pt that is slightly offset from its default position. Boldfacing and changing font size makes it easier to see text on individual computer screens and in the classroom. The final version of this Animator applet is shown below.

 

 

 

Figure 5: Final projectile motion applet.

 

Scripting Motion With Forces

The previous section animated a red ball based on knowing the ball's trajectory. This amounted to the author solving the problem in order to specify the ball's position at any given time. In this section a red ball will again move, but now subject to a force field scripted by the author.  Replace the setTrajectory statement in the projectile script with the following statement:

 

document.animator.setForce(id1,"0","-9.8", 0,0,8.55,23.5);

 

The argument of setForce is has the following signature:

 

setForce(id,Fx,Fy,x0,y0,vx0,vy0);

Here the object set to experience the force is again the red ball, id1. Fx and Fy are strings representing the component of the force in the x and y directions, respectively. These forces must appear in the setForce method with quotes around the function as they are strings. The force can depend on x, y, vx, vy, and t, but in all cases, must be a string. The following four arguments set the initial position of the object in x and y coordinates followed by the initial velocities in the x and y directions, respectively. These values are not strings but can be any number. In this example, the red ball will experience a linear restoring force, "-9.8 solely in the y direction, starting out at the origin and have an initial velocity components of 8.55 and 23.5.

It is easy to change the type of problem being displayed by changing the force function. In order to study simple harmonic motion start with the html page used in the previous example and change the script as follows:

<html>

<head>

<script language="JavaScript">

function shm1_0(){

document.animator.setAutoRefresh(false);

document.animator.setDefault();

document.animator.setPixPerUnit(5);

document.animator.setGridUnit(2);

id1=document.animator.addObject("circle","r=10,m=1")

document.animator.setForce(id1,"-2*x","0",20,0,0,0);

document.animator.setRGB(id1, 255,0,0);

document.animator.setOneShot(0,2.3, "End of Animation");

document.animator.setTrail(id1,150);

document.animator.setFootPrints(id1,2);

document.animator.setGhost(id1,true);

document.animator.setAutoRefresh(true);

document.animator.forward();

}

</script>

<title>Projectile</title>

</head>

<body bgcolor="#FFFFFF">

<h3 align="left">Simple Harmonic Motion</h3>

<p align="center">

<applet codebase="../classes/" code="animator4.Animator.class" archive="Animator4_.jar,STools4.jar"

align="baseline" width="400" height="100"

id="animator" name="animator">

<param name="FPS" value="10">

<param name="dt" value="0.1">

<param name="showControls" value="false">

</applet>

</p>

<p align="left"><a href="JavaScript: shm1_0()">Start</a> </p>

.

.

</body>

</html>

Script 2: Simple Harmonic Motion.

 

and then add the standard VCR buttons as in the previous examples. The ball will move in one dimension so in the applet tag the width and height of the applet window has been changed and the shiftPixOrigin line has been removed to better show the simple harmonic motion soon to be scripted. To distinguish this script from the projectile script, the name of the function has been changed to shm1_0(). Finally, the animation is set to run for a half cycle of the motion (2.3 seconds) and will stop and display "End of Animation" with the setOneShot method.

 

The line

 

document.animator.setForce(id1,"-2*x","0",20,0,0,0);

 

sets the force that the ball will experience to be a linear restoring force, F= -x. . For some visual feedback, add ghosts:

 

document.animator.setTrail(id1,150);

document.animator.setFootPrints(id1,2);

document.animator.setGhost(id1,true);

 

below the setRGB line, and the following applet should appear on your web browser:

 

 

Figure 6: Simple harmonic motion applet with ghosts.

 

Thus far, the animation is simple harmonic, but there is no spring. To add a spring in this context, three additional lines must be added to the script. First, comment off or remove the last three lines added since the trail and the ghosts will get in the way of the spring. Then add:

 

id2=document.animator.addObject("rectangle",

"w=10,h=40,x=-30");

document.animator.setRGB(id2,0,0,0);

document.animator.addConnectorSpring(id1,id2);

 

to the script. The first addition adds a rectangular anchor for the spring. The second line makes the anchor black and the final line connects a spring from the ball to the anchor.

Finally, change the animation time in the setOneShot command to 13.4 so the animation will run through three cycles and look like this:

 

 

Figure 7: Simple harmonic motion applet with spring and anchor.

 

Note that since only the red ball knows about the force, the anchor rectangle is indeed an anchor and does not move in response to the setForce method.

 

 

Simple Harmonic Motion Applet Sample Problems

The basic simple harmonic motion applet is now complete. New scripts can be written by varying the spring constant and the mass of the red ball. One can ask questions involving mass, velocity, acceleration, work, kinetic and potential energy, spring constant, and period.

 

For example, by changing the arguments of the setForce and setOneShot commands to:

 

document.animator.setForce(id1,"-2*x-0.2*vx", "0",20,0,0,0);

document.animator.setOneShot(0,40,

"End of Animation");

 

damped harmonic motion arises from the original simple harmonic motion applet. Questions regarding kinetic energy, potential energy and energy loss can now be asked.

Dragging Objects and Slavery

Another set of additions can make the reader of the page interact even more closely with the applet. Consider the following additions to the script below the document.animator.setRGB(id1, 255,0,0); line:

 

document.animator.setDragable(id1,true);

document.animator.setConstrainY(id1,0,-18,18);

document.animator.setShowConstraintPath(id1,false);

tid=document.animator.addObject("text",

"text=drag me");

document.animator.setAnimationSlave(id1,tid);

document.animator.setDisplayOffset(tid,-20,15);

document.animator.setObjectFont(tid,"Hevetica",1,12);

 

and the following change to the setForce command:

 

document.animator.setForce(id1,"-2*x","0",0,0,0,0);

 

The idea is to have the red ball start out in equilibrium and have the reader of the web page drag the red ball out of equilibrium, let go, and watch the animation. The first line allows the reader to drag the red ball. Since this is a one-dimensional problem, the ball must remain at y=0 even when the student drags the ball. The next command setConstrainY does just that and also limits the red ball to -18<x<18 so as to keep the animation physical (no over stretching or bunching up of the spring). Since the constraint is a necessary feature, but will get in the way of the animation, setShowConstraintPath hides the constraint path. The next four lines place the text "drag me" in the animation. Another new method used is that of setAnimationSlave.  If the author of the script wants the text to follow the red ball, the text can be made a slave of the red ball (the red ball is its master). This means that wherever and however the red ball moves due to the input of the reader, the text must follow. The argument of this method is (id of master, id of slave). In fact, the slave will be placed in the center of the master object, and to make "drag me" more readable, setDisplayOffset and setFont are used to format the text. Since the ball now must be in equilibrium, the setForce command must place the red ball at the origin with no initial velocity.

 

 

Figure 8: Final dragable simple harmonic motion applet.

 

This applet is now an excellent "laboratory" to test, for example, how the period of simple harmonic motion depends on the amplitude. Instead of hearing the independence of the period, students can test this idea with several initial amplitudes and then measuring the period of motion.

 

These two examples have stressed the primary methods and syntax involved in writing an applet using Animator. Of course, not all of the methods in Animator were discussed. In fact, one of the most interesting and useful features of Animator, the fact that data (position, velocity, acceleration, and combinations of these) from an object can be sent to a graph was not discussed at all. For these details see the Data Connection section. For a full description of all the methods and their descriptions, see the Animator reference section and for more examples, see the CD.


 

 



[1] Animator versions 1 and 2 only supported objects following analytic trajectories.  These early versions were written for Java 1.0 and were designed to run on computers with 90 MHz microprocessors.  Animator 3 was written in Java 1.1 and required a 200 MHz processor in order to solve the differential equations for real-time dynamics.  Animator version 4 added inter-applet communication and introduced a consistent naming convention for adding objects to Physlets, the the addObject method.

[2] It is necessary to enter characters that have special meaning, such as < and >, using escape sequences.  The escape sequences for < and > are &lt; and &gt;, respectively.   In this example, escape sequences are used to inform the browser that we intend to render the symbols  < and > rather begin or end a tag.

[3] Units are important to physicists.  But, computer simulations store numbers and these numbers do not have units. Calculations are performed just as they are on a pocket calculator. This can cause confusion since the time and distance units shown on the computer display do not have an a priori relationship to the real world.  In other words, we can assign the relationship to be anything we want it to be.  For example, an animation modeling the motion of an electron about the nucleus of an atom will define the distance unit to be 10-9 meter, i.e. a hm,  and the time unit to be 10-6 second, i.e. a mm.  Another simulation might define distance and time units to be kilometers and hours, respectively.