Dateline: 9/27/00
To continue from the first part of this tutorial we now have a pretty boring world consisting of a cube with a point light source. You can click on the cube and the point light source turns on.
Next we're going to make the cube function a little better as a button by turning it into a toggle switch. You will click on the cube once and the point light will turn on, click a second time and it will turn off etc. etc.
In order to accomplish this feat we must introduce the dreaded Script Node. Script Nodes are containers of behavior. An english type description of our file so far looks like
#this is not VRML but an english-like description Transform { DEF ELMO TouchSensor Cube } PointLight {} ROUTE ELMO to PointLight.on
The behavior in a Script node is described using a scripting language typically javascript or java. We will use javascript. Let's call our Script "ToggleScript" and look at it:
DEF ToggleScript Script { field SFBool value FALSE eventIn SFBool set_boolean eventOut SFBool value_changed url "javascript: function set_boolean( bool, eventTime ) { if (bool == false ) { return; } if (value == true ) { value = false; } else { value = true; } value_changed = value; }" } ROUTE ELMO.isActive TO ToggleScript.set_boolean ROUTE ToggleScript.value_changed TO PointLight.set_on
To dissect the script we see that the script contains a single field called value. This field and the input and output events are booleans.
If the field receives a FALSE boolean event it returns a FALSE.
Only if the Script receives a TRUE event does it start to manipulate the value.
If the value is TRUE it get's set to FALSE.
If the value is FALSE it get's set to TRUE.
The value is copied to value_changed and that is the output event defined via the eventOut definition and that is sent to the "on" field of the point light Node.
Note that the name of the javascript function is set_boolean which is the same name as the eventIn. Routing the event into the field set_boolean calls the particular function matching the name of the eventIn. For the output the name of the eventOut field is called value_changed and setting the variable value_changed to a value sends the data out as the eventOut data.
Let's put it all together in a single file. Now our masterpiece button cube file
looks like:
Next Page
Finishing Up
>Page 1,2