Tutorial #3: Update Callback
This demo will show how you can use a simple callback function in order to update the objects on the screen. In the previous tutorial, we created a scene with one cube and a camera. In this tutorial we will create a line of cubes. Each of these cubes will be set spinning in turn. You can use the same html page from tutorial #2 to show this demo.
/*This demo creates 4 boxes in a row. The left most box will
start spinning immediately. The next box will spin 5 sec after
the page is loaded, the next one 5 sec after that etc.*/
var cam;
var totaltime;
var boxes=new Array();
var isspinning=new Array();
/*this callback function is used by the scene class. Every time
the scene is updated, it will get called. This function tests
the amount of time elapsed since the page was loaded and
start a new cube spinning every 5 sec.*/
function spincubes(time){
//totaltime stores amount of time passed since page was loaded
//time is in millisecond. Thus 5000 millisecond is 5 seconds.
totaltime=totaltime+time;
//once the 4th cube is spinning it is no longer necessary to check
if(isspinning[3]==false){
for(var i=0;i<4;i++){
if(isspinning[i]==false && totaltime > i*5000 && totaltime < 5000*(i+1)){
isspinning[i]=true;
boxes[i].setAngularVel(new Array(Math.random()*0.001,
Math.random()*0.001,Math.random()*0.001));
}
}
}
}
//the function that will be called by the web page canvasName is the name
//of the canvas where the scene will show.
function canvasMain(canvasName){
//create a new Scene object
var scn = new Scene();
totaltime=0;
//check that it was successful
if(scn.createScene(canvasName)){
for(var i=0;i<4;i++){
//create a cube. by default, this cube is centred at 0,0,0
boxes[i]=new Cube();
boxes[i].setPosition(new Array(-4.5+i*3,0,-20));
//Add the object to the scene
scn.addObjectToScene(boxes[i]);
//the box is not currently spinning
isspinning[i]=false;
}
//create a camera
cam = new FreeCamera();
//set the camera position
cam.setPosition(new Array(0,0,0));
// make it look into the scene (remember +ve z in a right handed system is
//pointing out of screen, so -ve z is pointing in
cam.setLookAtPoint(new Array(0,0,-10));
//add the camera to the scene
scn.addCameraToScene(cam);
//add the callback function
scn.setUpdateCallback(spincubes);
//start the scene
scn.startScene();
}
} 