To Search this document use Command-F. Note: This is a dynamic document with notes of things that need to be changed or fixed. Check back often.

Faq's

How do I save my work.

Pressing the save button above the editor will download what's in the editor to your hard drive.

How do I share my project with someone?

You can send them the code to paste into the editor, or you can put the code up on server and load it from a link.
Example: https://cinematicsciences.com?url=yourservername.com/yourgame.js

This seems kind of buggy. I have to press Run more than once sometimes.

We're still getting the bugs out after switching to the Unity platform. It's getting more stable each week.

I thought there would be more content.

We're porting content from the original version and new content every month. Look for more content in our monthly updates.

Can I add my own models?

We're currently looking into the ability to add your own models and experimenting with different formats. Look for this capability in 2024.

Some of the features in the documentation are not working.

If you find something that is not working correctly or documented incorrectly, you can email a message to us, or post a question on stack overflow.

Are you going to have a community of developers who can talk to each other.

We're looking into that for mid 2024.

Basic Building

How do I use the Editor?
What kinds of objects can I load?
How do I position and rotate an object when it's loading?
How do I position, rotate and scale an object after it's loaded?
How do I get a camera to follow an object or two objects?
How do I change physics properties like friction,mass,velocity,angular velocity etc...
How do I change gravity?
How do I control the jeep and other special objects?
Can you teach me how to learn JavaScript?

Advanced Building

How do I position objects near other objects?
How do I build a tower of blocks using a for loop?
How do I check whether an object collided with another object?
How do I control the simulation speed?
How do I run my own function every second?
How do I make User Interfaces like buttons, sliders, and inputs?
How can I change the scenery and background?
What kinds of Visual Effects can I add
Do the characters have animations I can use?
Can I animate an object?

User Experience

Goals, Rewards, linking to Quizzes, Surveys
How do I set a goal that the user can reach and check that they reached it?
How do I show another webpage?
How do I reward a user?

Expert Building

How can I build my own machines?
IK Animation

Scientists

How can I Visualize Data
Can I change the shape of an object?
Global Variables
Rotations Eulers vs Quaternions
How do I make Meters, Points, and Graphs
Vector and Rotation Math
I want to use my own javascript library

Fun Features

Interactive Character Dialogue
Behaviors
I want to do some Interactive Fiction Programming

More Topics

To Search this document for other topics use Command-F

Editor Basics

Top Buttons

Run:Runs the code. Note this is somewhat buggy sometimes you have to hit it twice because the old code is not garbage collected. If it doesn't look right hit it again.
Run+: Adds code to the current scene
//: Comment or Uncomment
Binoculars: Find/Replace
Undo
Redo
Font-Size: Change the Font
Right Arrow: Go to Line

Bottom Buttons

Cmd: A command line interface for typing in single lines of code.
Run+:Runs the Code in the Command Line. Pressing Enter will also Run the code.
History:Shows a history of all commands used this session.

go to top




Objects: Check back Weekly for new objects

Search Items


go to top


Loading and Positioning Objects

load(type,name,x,y,z,rx,ry,rz)

Loads an object with optional position and rotation

Parameters:

type:string a known object type like 'box'

name:string a name like 'box1',

x,y,z:num x,y,z of a vector

rx,ry,rz:num x,y,z of a rotation vector

Example:

load("box","box1");//without position or rotation
load('box','box2',0,10,0); //with positioning only
load('box','box2',0,10,0,0,90,0);//with 10 for y position and 90 for y rotation.
load('box','box2',0,0,0,0,90,0);//with 0,0,0 for position and 90 for y rotation
//build a tower using a for loop to load 10 boxes;
for(var i=0;i<10;i++){
  load('box','box'+i,0,1+i,0);//1 is added to the y position so the first box will not be in the ground
}

go to top


Setting Position, Rotation and Scale After Loading

Example:

load('box','box1');//Once and object is loaded you can refer to it by name
box1.setPosition(0,10,0);
box1.setRotation(0,45,0);
box1.setScale(2,2,2);
//you can also set them directly
box1.pos.x=5;
box1.rot.y=90;
box1.scale.x=2;
//or with vectors
box1.pos=vector(0,2,0);
box1.vel=vector(2,0,0);
box1.scale=vector(1,1,1);
//note do not scale the animals, they have joints and do not scale.

	

go to top


Position by Reference

These commands allow you to position objects using a second object as a starting point.

//position an object based on another object 
//for the first object we use box1. For the second object we use box2
load('box','box1');
load('box','box2');

//put box1 ontop of box2 and other feats.
box1.ontop('box2');
box1.onbottom('box2');
box1.onleft('box2');
box1.onright('box2');
box1.infront('box2');
box1.inback('box2');
box1.ontop('box2',0,1,0);//an additional x,y,z can be added to adjust the position.
ontop("box1","box2",0,1,0);//another way to call ontop

go to top


Cameras

setCamera(targetname, tracktype, startzoom, xoffset, yoffset, zoffset,endzoom,duration,stationary,type)

Sets the camera type

Parameters:

targetname:string like 'penguin' the name of whatever you want to track.

tracktype:string like 'track' or 'follow' track points the camera to the object, follow moves with the object

startzoom:number: Set the camera zoom lens for example 25 for a wide angle lens and 75 for zoom lens

xoffset,yoffset,zoffset:number how far you want the camera to offset from 0,0,0 like yoffset 15 which means the camera is 15 units up

Example:


setCamera("penguin","follow");
setCamera('penguin','follow',30,0,0,10);//follows with a wide angle lens of 30 and staying about 10 meters away from the Z direction.
setCamera("penguin","track");

go to top


Follow 2 objects at once

dynamicZoomOn(object1name, object2name)

Tries to Dynamically zoom in and out to keep both objects in the view.

Parameters:

object1name:string like 'penguin' the name of whatever you want to keep in view.

object2name:string like 'jeep' the name of whatever second object you want to keep in view

Example:

dynamicZoomOn('penguin','jeep')

go to top


controlCamera() or releaseCamera()

Allows you to control the camera with the mouse and keys. Hold shift and move the mouse to dolly the camera up or down, Hold option to pan left right up down

Example:


controlCamera();//allows you to control the camera with the mouse or arrow keys
releaseCamera();//you can no longer control the camera with the mouse or arrow keys

go to top


Gravity

setGravity(g)

sets the gravity for every object in a scene

g:number or stringearth,moon,zerog, or a number like -9.81,0,-1 etc.

Example:


setGravity("moon");
setGravity("zerog");
setGravity("earth");
setGravity(-10);

go to top


Physics

Physics properties or functions you can use or set on all objects


//for these examples we use box1
load('box','box1'); 

//position
box1.pos=vector(0,0,0);
box1.pos=vector();
box1.pos.x=0;
box1.pos.y=0;
box1.pos.z=0;
box1.setPosition(0,0,0);


//rotation
box1.rot=vector(0,0,0);
box1.rot=vector();
box1.rot.x=0;
box1.rot.y=0;
box1.rot.z=0;
box1.setRotation(0,0,0);

//scale
box1.scale=vector(1,1,1);
box1.scale=vector();
box1.scale.x=1;
box1.scale.y=1;
box1.scale.z=1;
box1.setScale(1,1,1);//a scale of 0,0,0 means the object will disappear.

//velocity
box1.vel=vector(0,0,0);
box1.vel=vector();
box1.vel.x=0;
box1.vel.y=0;
box1.vel.z=0;
box1.setVelocity(0,0,0);

//angular velocity
box1.angvel=vector(0,0,0);
box1.angvel=vector();
box1.angvel.x=0;
box1.angvel.y=0;
box1.angvel.z=0;
box1.setAngularVelocity(0,0,0);

//acceleration 
//note this is added to the gravity force. Use gravityOff("box1") to remove gravity.
box1.acc=vector(0,0,0);
box1.acc=vector();
box1.acc.x=0;
box1.acc.y=0;
box1.acc.z=0;
box1.setAcceleration(0,0,0);

box1.zero();//this will reset the position, rotation, velocity, angular velocity and acceleration to vector(0,0,0).

//mass
box1.mass=10;

//friction and elasticity
box1.friction=1;//between 0 and 1. 0=no friction.
box1.setFriction(.5);
box1.setElasticity(0);//between 0 and 1. 1 is bouncy.

//positioning an object based on another object for the second object we use box2
load('box','box2');

//put box1 ontop of box2 and other feats.
box1.ontop('box2');
box1.onbottom('box2');
box1.onleft('box2');
box1.onright('box2');
box1.infront('box2');
box1.inback('box2');


//freeze an object so it won't move
box1.freeze();//box1 will no longer move with physics
box1.unfreeze();//box1 will move with physics
//prevent motion on z axis for 2D physics.
box1.setConstraints('z'); //object cannot move in z direction.
//note by default many objects like the penguin are already constrained in z
//to release them type in the following code
box1.setConstraints("none");//object can move in any direction.

go to top


Objects with Special Functions

Jeep: setSteering,setSpeed,getSpeed

Example:

load('jeep','jeep');
jeep.setSteering(angle);//angle=a number;
jeep.setSpeed(amount);//amount=how fast the wheels turn
jeepspeed=jeep.getSpeed();//returns the speed of the jeep wheels;
//example user interface controls for the jeep
createSlider('jeepgas','speed',"jeep.setSpeed",-10,100,1,0,"true");
createSlider('jeepsteer','steer',"jeep.setSteering",-60,60,1,0,true);

go to top


Cannon: setAngle, setGunPowder, load, fire

Example:

load('cannon','cannon');
cannon.setAngle(30);//angle=a number;
cannon.setGunPowder(10);//amount=how much gunpowder does the cannon use to fire the cannonball.
cannon.loadObject(objectname);//you must set a loadObject before you can fire the cannon
cannon.fire();//fires the cannon
//example user interface controls for the cannon
createButton('cannonfire','fire','cannon.fire()');
createSlider("cannonangle","angle",'cannon.setAngle',0,130,1,0);
createHtmlButtonWithInput("cannonpowder","gunpowder",'cannon.setGunPowder',200);

go to top


Catapult: angle,tension,load,launch

Example:

load('catapult','catapult');
catapult.angle(30);//angle=a number;
catapult.tension(10);//amount=the strength of the spring that launches the catapult
catapult.load(name);//name of object you want to load into the catapult.
catapult.launch();//launches the catapult contents

go to top


Pendulum:

Example:

load('pendulum','pen');
pen.setAngle(90);
pen.setWeight(100);
pen.setLength(20);
pen.drop();
pen.setWeightObject('opencrate');//changes the object from a ball to whatever object you enter
pen.hidePendulumPost();
pen.showPendulumPost();
pen.pendulumPostCollide();
pen.pendulumPostDontCollide();
pen.breakJoint();
pen.remakeJoint();

go to top


communicationstower:

Example:

load('communicationstower','ct');
ct.setSpeed(10);//sets satellite speed

go to top


Spherebot: Your personal robot drone. You can control all physics except position

load('spherebot','sb');
sb.scale=vector(2,2,2);
sb.mass=10;
sb.velocity.y=10;
sb.moveTo(vector(0,0,0));//moves to the position given by a vector.
see the object physics section for more commands, but remember you cannot change spherebot's position.

go to top


Collisions

collisionWatch(object1name, object2name, enterfunc, exitfunc)

Checks for Collisions between object1 and object2 and runs functions when the objects enter or exit the collision

Parameters:

object1:object like box1 or penguin1

object2:object like box2 or penguin2

enterfunc: function name that is called when two objects enter a collision.

exitfunc: function name that is called when two objects exit a collision.

Example:


collisionWatch('penguin','box1','onEnter','onExit');

function onEnter(){
	log('enter');
	}
function onExit(){
	log('exit');
	}

go to top


Joints

Joints are used to connect objects together. They initially start out like a steel rod, but you can change the joint properties to make a spring, a shock absorber, a swivel, a hinge, a motor etc. The joint code is based on the PHYSX D6 joint or the unity configurable joint. These joints are so confusing that most people avoid them. But you can create really cool stuff if you're patient. Before setting joints move them into the positions and rotations first and then freeze everything. Joints have to be created in a separate function call. If you try to create them when they are being loaded, positioned or frozen they will not work. After the joints are made unfreeze the parts.


createJoint(object1,object2)

Creates a locked Joint between two objects. Initially all the joint parameters will be locked. The joint will have no movement and the two objects will act like they are connected by a steel bar. The order matters too. Initially joints are connected at the center of mass of each object unless you change the anchor and axis settings below.

Parameters:

object1:object like box1

object2:object like box2

Example:

createJoint(box1,box2)

go to top


Working with joints

When a joint is created it is named after the two objects you connected. For example a joint connecting box1 and box2 will become box1box2. Joints have many properties and you can make all sorts of machines out of joints.

Examples:


//create a joint
createJoint(box1,box2);//creates a locked joint between box1 and box2 called box1box2.

//remove a joint
removeJoint(box1box2);

axis and anchors

//axis and secondaryaxis
/*In general you do not need to set this unless your joints are going to be at angles.  
If you don't set this then (xyz)LinearMotion and (xyz)AngularMotion of the joint will correspond to the same world x,y,z directions. If you do set this then X is no longer the world X, it's now the axis you set, and (xyz) LinearMotion and (xyz) AngularMotion of the joint will now no longer correspond to world xyz. In fact whatever axis you set will become the new X axis.  Confused? You can think of the X,Y,Z axis as placeholders like 1,2,3 where 1 is the axis you set, 2 is the secondary axis you set, and 3 is the axis that's perpendicular two 1, and 2.  If you set the axis as 0,1,0 which is world Y. The X axis in xLinearMotion and xAngularMotion will now correspond to Y.  After axis is set the secondaryaxis you set will correspond to yLinearMotion and yAngularMotion. zLinearMotion and zAngularMotion will default to the axis perpendicular to the first two you set.  So it will make it really confusing because X is no longer X world space. If you don't set axis it defaults to XYZ worldspace if you set them x,y,z will now map to axis, secondaryaxis, and axis perpendicular to the first two. Yes it's very confusing but that's the way PhysX and Unity set it up. This is one reason why very few people use it. 

box1box2.axis=vector(1,1,0);
box1box2.secondaryaxis=? find a perpendicular to your first axis.
//Remember once these are set it xLinearMotion and xAngularMotion and y and z no longer correspond to the world x,y,z.
//Developers Note: I might Change these to firstAxis, secondAxis, and thirdAxis on another build.

//anchor
//where the joint starts
//automatically set as the midpoint between the two objects but you can set it manually
//if you want to have the joint rotate around the first object as the center make the anchor=vector(0,0,0);
//if you want the joint to rotate around the second object make the anchor the position from the first object to the second
//for example if the first object is at 0,0,0 and the second is 5,0,0
//make the anchor be vector(5,0,0);
box1box2.anchor=vector(5,0,0);
box1box3.anchor=vector(5,5,0);


Motion along the axis of the joint
//xLinearMotion, yLinearMotion, zLinearMotion choices are free,limited,fixed
//this is the motion allowed on the different axis
box1box2.xLinearMotion='free';
//the boxes will move freely on the axis between them.
box1box2.xLinearMotion='limited';
//the boxes will move in a limited way on the axis between them after you set the limits.
box1box2.xLinearMotion='fixed';
//the boxes will not move relative to each other on the axis between them.

Rotation around the axis of the joint
//xAngularMotion, yAngularMotion, zAngularMotion choices are free,limited,fixed
//this is the rotational motion allowed on the different axis
box1box2.xAngularMotion='free';
//the boxes will rotate freely on the axis between them.
box1box2.xAngularMotion='limited';
//the boxes will rotate in a limited way on the axis between them after you set the limits.
box1box2.xAngularMotion='fixed';
//the boxes will not rotate relative to each other on the axis between them.

Motion limits
//xLinearLimit,yLinearLimit,zLinearLimit
//Limits how far along the axis a connected object will move.
//each limit has other properties such as bounce, spring, damper that change
//what happens when the object reaches the limit.
box1box2.xLinearLimit=5;//box2 will only move 5 units away from box1 before it hits a limit
box1box2.xLinearLimitBounce=0;//how bouncy the limit is
box1box2.xLinearLimitSpring=500;//how springy the limit is
box1box2.xLinearLimitDamper=500;//how much shock absorption the limit has

Rotation limits
//xAngularLimit,yzAngularLimit
//Limits how much of an angle the joint will rotate
//each angular limit has a high and low value and bounce, spring, and damper settings
box1box2.xAngularLimitLow=-45;
box1box2.xAngularLimitHigh=45;
box1box2.xAngularLimitLowBounce=0;
box1box2.xAngularLimitHighBounce=0;
box1box2.xAngularLimitLowSpring=500;
box1box2.xAngularLimitLowDamper=500;
box1box2.xAngularLimitHighSpring=500;
box1box2.xAngularLimitHighDamper=500;

//Note: Y and Z rotations have only 1 limit, not low and high. It is usually set
//around 0. So 90 would be -45 to 45. If you want to have a low and high setting
//you'll need to explore the axis and secondaryaxis settings because only X has a low and high setting choice.
box1box2.yAngularLimit=45;
box1box2.zAngularLimit=45;
box1box2.yAngularLimitBounce=0;
box1box2.zAngularLimitBounce=0;

//The spring and damper settings for Y and Z are lumped together as yz this is confusing and if you put in
//yAngularLimitSpring and zAngularLimitSpring it will not function correctly you have to use the weird yz.
//this is another reason no one wants to use these joints but it's part of the PHYSX physics engine.
box1box2.yzAngularLimitSpring=500;
box1box2.yzAngularLimitDamper=500;
//Developers Note: I may separate them for the user but then combine them in the underlying code to get rid of this confusion in another build.


Linear Drives Springs and Motors
//you can drive motion on the linear axis using a spring or motor or combo of both.
//linear spring drives drive toward a targetPosition on the axis
//linear motor drives drive towards a targetVelocity
//a spring is initially set to wherever the joint is made, that's it's resting state.
//if you try to move it from the resting state it will spring back. You can reset
//the resting state by using the targetPosition.

//a motor that moves on the main axis at a velocity of 5 m/s
box1box2.xLinearDriveMotor=500;
box1box2.xLinearDriveSpring=0;
box1box2.xLinearDriveForce=5000;//max force to use
box1box2.targetVelocity=vector(5,0,0);//sets the motor to move at a speed of 5 on the main axis

//a spring that moves on the main axis and doesn't want to move away from 5 on the main axis
box1box2.xLinearDriveMotor=0;
box1box2.xLinearDriveSpring=500;
box1box2.xLinearDriveForce=500;//max force to use
box1box2.targetPosition=vector(5,0,0);//tries to set the new resting state at 5,0,0 on the X axis. 
//make sure you set the resting state vector along the correct axis.

Angular Drives, Motors and Springs
//xAngularDrive,yzAngularDrive
//you can drive rotation around on the x axis using a spring or motor or combo of both.
//angular drive spring drives toward a targetRotationXYZ
//angular drive motor drives towards a targetAngularVelocity

//example motor that spins at 10 m/s around the main axis
box1box2.xAngularDriveMotor=500;
box1box2.xAngularDriveSpring=0;
box1box2.xAngularDriveForce=5000;//max force to use
box1box2.targetAngularVelocity=vector(10,0,0);//motor tries to spin at 10m/s

//a spring around main axis that doesn't like to be moved from it's target rotation
box1box2.xAngularDriveMotor=0;
box1box2.xAngularDriveSpring=500;
box1box2.xAngularDriveForce=5000;//max force to use
box1box2.targetRotationXYZ=vector(45,0,0);//spring is set at 45 degrees

//Y and Z axis are lumped together in yzdrive
box1box2.yzAngularDriveMotor=500;
box1box2.yzAngularDriveSpring=0;
box1box2.yzAngularDriveForce=5000;//max force to use
//Developers Note: I May separate these for the user and then combine in code.

//there is also a slerpDriveMotor,Spring, and Force you can use to move
//you'll have to look up slerp on google to find out what it is and I'm not
//sure if I included the target. 
//Developers Note: Check to see how slerp target rotation works.
box1box2.slerpDriveMotor=500;
box1box2.slerpDriveSpring=0;
box1box2.slerpDriveForce=5000;//max force to use

Breaking Joints
//breaking joints
//these are the forces and torques which will break the joints
box1box2.breakForce=1000;
box1box2.breakTorque=1000;
//If you want more info about these joints you can look up the Unity configurable joint
//and/or Physx or Unreal D6 joint, the names will be slightly different but you can the basic ideas from reading
//tutorials that use this same joint system which originally came from the PHYSX physics engine.

go to top


Simulation Controls

pause()

Pauses the simulation

none:none

Example:


pause();

go to top


unpause()

un-Pauses the simulation

none:none

Example:


unpause();

go to top


simSpeed(speed,time)

Changes the simulation speed. Normal speed is 1. Try .25 and 2

amount:number

time:numberoptional how long you want the speed to change in seconds, after which it will go back to normal at 1.

Example:


simSpeed(.25,3);//a slowmotion effect at 1/4 speed for 3 seconds.
simSpeed(2,1);//a fast motion effect at 2x speed for 1 second.
simSpeed(1); //change the speed to 1 with no time limit.

go to top


holdAll()

Changes every object to fixed so it won't move

Parameters:

Example:


holdAll();

go to top


releaseAll()

Releases every object from fixed so they will move again

Parameters:

Example:


releaseAll();

go to top


runInBackground(bool)

Allows the program to run in the background when the browser is hidden.

bool:true/false true or false

Example:


runInBackground(true);

go to top


Scene

setSky(name)

Changes the sky to a different type

Parameters:

name:string Type of sky. Examples:'bluesky','Galaxy3'

Example:

setSky('bluesky');

go to top


showAxes()

Shows the XYZ axis

Example:

showAxes();

go to top


hideAxes()

Hides the XYZ axis

Example:

hideAxes();

go to top


showStage()

The stage is the ground plane you can show or hide it

Example:

showStage();

go to top


hideStage()

Hides the ground plane

Example:

hideStage()

go to top


grid()

Shows a grid. Not implemented yet.

Parameters:

type:string Type of grid. Examples:english,metric

multiplier:number Multiplier of grid. Examples:10,100,.1,.01

Example:

grid('english',100);

go to top


Visual Effects

addVfx(who,what)

Attaches a visual effect to an object

Parameters:

who:string which object you want to apply the visual effect to. Examples: 'world','penguin1','box1'

what:string the name of the visual effect you want to add examples include 'smoke','fire','snow'

Example:

addVfx('box1','smoke');

go to top


removeVfx(who,what)

Removes the visual effect

Parameters:

who:string which object you want to remove the visual effect from

what:string the name of the visual effect you want to remove

Example:

removeVfx('box1','smoke');

go to top


addCameraFx(what)

Shows a camera visual effect

Parameters:

what:string the name of the visual effect you want to add examples include 'bloom','sepia','motionblur'

Example:

addCameraFx('bloom');

go to top


removeCameraFx(what)

Removes the camera visual effect

Parameters:

what:string the name of the visual effect you want to remove

Example:

removeCameraFx('bloom');

go to top


explode(force,x,y,z,radius,yadjust)

Causes an explosion at x,y,z with radius r

force:number strength of the force

x,y,z:x,y,z position of the center of the explosion.

radius:number radius of the explosion. The explosion will only affect things within this radius.

yadjust:number optional y axis adjustment to the explosion center. yadjust of -5 moves the explosion down by 5 so it throws objects higher.
yadjust of 0 will explode objects outward from the source but not upward. You can also make the adjustment in the x,y,z yourself and leave out the yadjust parameter

Example:


box1.pos=vector(0,0,0);//box1 position
explode(50,0,0,0,10,-5);//an explosion with force 50 centered at position vector(0,0,0) with a radius of 10 and y down -5;

go to top


Character Animations

//the penguin and seagull do not have predefined animations.
The cow (coming soon mooooo!) will have animations like run, walk, idle, etc. 
//the structure to play an animation will be
  playCharacterAnimation(charactername,whichanimation,speed);
  //examples
  playCharacterAnimation("cow","walk",1);
  stopCharacterAnimation("cow");

go to top


Animating Objects

object.animateJoint(what, x, y, z, t, func,param)

If an object is a character you can animate the character's joints

what:string what joint you want to animate

x,y,z:numbers for x,y,z axis joint rotations

t:number how long you want the animation to take in seconds,

func:string name of a function you want to run after the animation is over,

param:any a parameter you can send with the function

Example:


load('penguin','penguin1');
penguin1.animateJoint('lHand',0,90,0,5)
penguin1.animateJoint('lHand',0,90,0,5,'done',5);
function done(x){
	alert(x)
}
//will animate the lHand changing the rotation 
//of the y angle 90 degrees in 5 seconds. 
//Then it will call the function 'done' and will 
//send 5 to the function.
//the result will be the lHand will move then when it's done 
//it will alert 5

go to top


object.animateMove(x,y,z,t,func,param)

Animates a position change. Please note to set the object's acceleration in the y direction to 0 before using object.animateMove
otherwise the acceleration physics will fight the movement animation.
While an object is moving with animationMove it will not experience regular physics
and may give unexpected results. If you want realistic physics please move objects by changing their velocity or acceleration.

x,y,z:numbers for x,y,z positions

t:number how long you want the animation to take in seconds,

func:string name of a function you want to run after the animation is over,

param:any a parameter you can send with the function

Example:


load('box','box1');
box1.acc.y=0;
box1.animateMove(0,2,0,5);
//will animate the movement of the box1 2 units in the y direction 
box1.animateMove(0,2,0,5,done,5);
//will do the same, but will also call the function 'done' 
//with parameter 5 after the animation is over.

go to top


object.animateRotate(x,y,z,t,func,param)

Animate a rotation change. While an object is moving with animateRotate it will not experience regular physics and may give unexpected results. If you want realistic physics please rotate objects by changing their angular velocity.

x,y,z:number for x,y,z rotations

t:number how long you want the animation to take in seconds,

func:string name of a function you want to run after the animation is over,

param:any a parameter you can send with the function

Example:


load('box','box1');
box1.acc.y=0;
box1.animateRotate(0,45,0,5);
//will rotate box1 45 degrees in the y direction in 5 seconds. 
box1.animateRotate(0,45,0,5,done,5);
//will do the same, but will also call the function 'done' 
//with parameter 5 after the animation is over.

go to top


object.animateScale(x,y,z,t,func,param)

Animates a scale change. While an object is moving with animateScale it will not experience regular physics and may give unexpected results. Note: normal scaling for x,y,z is 1,1,1 not 0,0,0. A scale of 0 in any direction will cause the object to have a thickness of 0 in that direction.

x,y,z:number for x,y,z scale default is 1,1,1 not 0,0,0

t:number how long you want the animation to take in seconds,

func:string name of a function you want to run after the animation is over,

param:any a parameter you can send with the function

Example:


load('box','box1');
box1.acc.y=0;
box1.animateScale(0,2,0,5);
//will animate the scaling of box1 in the y direction 
box1.animateScale(0,45,0,5,done,5);
//will do the same, but will also call the function 'done' 
//with parameter 5 after the animation is over.
 

go to top


IK Animation

startIK(name,jointname)

Start inverse kinematics animation. You specify a joint to be controlled and it is controlled with a goal1 object which is loaded with the animal objects. So for a penguin named 'penguin' the goal1 object would be 'penguingoal1'. For a horse named 'seabiscuit' the goal object would be 'seabiscuitgoal1'. You can move the goal1 object with regular physics or the object.animate command.

Parameters:

name:string the name of the object you want to move

jointname:string the name of the joint you want to control

Example:

//joint names to choose from include: lHand,rHand,lFoot,rFoot,head
startIK('penguin','lHand');
penguingoal1.pos.x=5;//moves the goal1 to 5
//The hand should follow the goal.
penguingoal1.animateMove('vel',5,0,0,10);

go to top


endIK(name)

Turn off IK

Parameters:

name:string End inverse kinematics animation for this object.

Example:

endIK('penguin1');

go to top


Timed Events

createInterval(func,time,param)

provide a function name, and the time between tests in milliseconds. The function must exist before check is called

Parameters:

func:string,function you want to call in quotes like 'moo'

time:number milliseconds 1000 for 1 second or 5000 for 5 seconds

param:any optional parameter you want to send with the function could be a string or number or object or array

Example:

function moo(){
	if(cow.vel.y>10){
	alert('mooooo');
	}
}
createInterval('moo',1000) 

go to top


deleteInterval(func)

Deletes an interval by the function name provided when you created the interval.

Parameters:

func:string

Example:

deleteInterval('moo') 

go to top


deleteAllIntervals()

Deletes all intervals

Parameters:

none

Example:

deleteAllIntervals() 

go to top


createCountdownTimer(func,time)

Creates a countdown timer. You provide the function name that you want to call at the end of the countdown, and the time to countdown in milliseconds

Parameters:

func:string

time:number in milliseconds

Example:

createCountdownTimer('moo',5000)

go to top


deleteCountdownTimer(name)

Deletes a countdown timer with the name you gave when you created it

Parameters:

name:string

Example:

deleteCountdownTimer('moo') 

go to top


startTimer(name)

Creates a timer with the name you provide

Parameters:

name:string

Example:

startTimer('mytimer')

go to top


stopTimer(name)

stops a timer with the name you provided in startTimer

Parameters:

name:string

Return: time:number in milliseconds that has passed between calling startTimer and stopTimer. Return

Parameters:

Example:

timesofar=stopTimer('mytimer');
alert(timesofar);

go to top


Behaviors

createBehavior(id, condition, change, limit, waitforfalse)

Creates a behavior. A behavior checks to see if a condition is true. If the condition is true it runs whatever is in the variable called change. Behaviors have two other parameters called limit and waitforfalse. Limit tells how many times you want the behavior to run before it quits. A limit of 1 will run the behavior 1 frame then turn off. A limit of 0 will run the behavior every frame. Set waitforfalse = 1 if you want to only run the change the first time the condition is true. It will not run the change again until the condition is false, then it will turn it back on.

id:number

condition:code in quotes that you would normally put inside an if statement to see if something is true or not,

change:code in quotes that you want to run when the condition is true.

limit:number how many times you want the behavior to run before it turns off. 1 will run just one time. 0 will run every time.

waitforfalse:1 or 0 1 will turn it on. 0 will turn it off.

Example:


createBehavior(1,'cow.pos.y>10','cow.animation='walk'',0,true);
/*will play the walk animation if cow's height is > 10.
waitforfalse is 1 so once the cow.pos.y>10 it will no longer 
change the animation to walk until the cow position is not > 10.
Then it will turn it on again.
*/

go to top


deleteBehavior(id)

Deletes a behavior by id number.

id:number

Example:


deleteBehavior(1);

go to top


Chat

penguin.chat(to,message);

A method for sending a chat to a character and getting back a response.

Parameters:

to:string the name of the object you want to send the message to. For example 'penguin'.

message:string A text message

Example:


//first load two characters
load('penguin','joe');
load('penguin','moe');

//here is the start of the chat
joe.chat('moe','how is your meowser?');

//Before this will do anything, we have to make responses for the characters.
joe.chat.responses['how/cat']='My cat is a jerk'
joe.chat.responses['good']='Awesome!'

moe.chat.responses['how/cat']='My cat is cool!'
moe.chat.responses['good']='Oh that's fine'

//and add any synonyms to be replaced during the chat processing. Synonyms replace slang words with a common word before the response is analyzed for keywords
chatSynonyms['good']='swell/cool';//replaces swell or cool with good
chatSynonyms['cat']='feline/kitty cat/meowser';//replaces meowser or kitty cat with cat

//now we can have a chat...
joe.chat('moe','how is your meowser?');
//will trigger the following conversation...
//moe: My cat is cool!
//joe: Awesome!

//Here's how it works
//first synonyms are replaced. Meowser is replaced with cat and 'how is your cat' is sent to moe.
//Then the chat system looks through all of moe's responses for keyword matches.
//In moe's first response the keywords 'how' and 'cat' match the 'how' and 'cat' in the message so we send the response: 'My cat is cool.' back to joe.
//Now the receiver is joe. and the message is 'My cat is cool';
//the synonym 'cool' is replaced with 'good'.
//Joe's responses contain a keyword match for 'good' and that is 'Awesome';
//This is then sent back to moe
//Since there are no keyword matches for Awesome in any of moe's chat responses, the conversation ends.

go to top


Visualizing Data

vectorViewer(name, type, showx, showy, showz, showr, k)

Attaches vectors to an object that scale with the magnitude of the type

Parameters:

name:string like 'box1','penguin1','joe'

type:stringtype of vector viewer includes 'position','velocity','pkenergy','acceleration'

showx,showy,showz,showr:number 1 for true, 0 for false like 1,0,0,0 for x axis only

k:number like .5 or .01. Use this constant to adjust the vectors if they are too big or too small.

Example:


setupvectorViewer('box1','velocity',1,1,1,0,.5);
//will show velocity vectors for the object multiplied by .5
setupvectorViewer('box1','pkenergy',1,1,0,0,.5);
//will show potential vs kinetic energy. 
//Potential energy on the y axis and kinetic energy on the x axis.

go to top


hidevectorViewer()

Turns off the vector viewer

Example:


hidevectorViewer();

go to top


createField(type, objectname, xstart, ystart, zstart, xstep, ystep, zstep, xtotal, ytotal, ztotal, xscale, yscale, zscale){

Creates a grid of vectors that can change their position,scale,rotation,and color

Parameters:

name:string type of object used at each field coordinate: 'vx' or 'gpuparticle' are current choices.

objectname:string world if you want space filling field in x,y,z or use an on object name like 'box1' if you want the field to be drawn on the outer mesh of the object.

xstart, ystart, zstart:number start in each coordinate

xstep, ystep, zstep:number step in each coordinate

xtotal, ytotal, ztotal:number total for each coordinate

xscale, yscale, zscale:number scale in each coordinate

Example:


createField('gpuparticle','world', 0, 0, 0, 1, 1, 1, 10, 10, 10, 1, 1, 1);
createField('gpuparticle','box1',0,0,0,1,1,1,10,10,10,1,1,1);

go to top


updateFieldPositions(array)

You provide an array and it will update the field positions. The array size is xtotal*ytotal*ztotal that you used for createField

Parameters:

array:array array of position vectors

Example:


updateFieldPositions(positionarray);

go to top


updateFieldRotations(array)

You provide an array and it will update the field rotations. The array size is xtotal*ytotal*ztotal that you used for createField

Parameters:

array:array array of rotation vectors

Example:


updateFieldRotations(rotationarray);

go to top


updateFieldScales(array)

You provide an array and it will update the field scales. The array size is xtotal*ytotal*ztotal that you used for createField

Parameters:

array:array array of scale vectors

Example:


updateFieldScales(scalearray);

go to top


updateFieldColors(array)

You provide an array and it will update the field colors. The array size is xtotal*ytotal*ztotal that you used for createField

Parameters:

array:array array of color vectors. Note color vectors have 4 parts (r,g,b,a) representing red,blue,green,alpha from 0-255

Example:


updateFieldColors(colorarray);

go to top


removeField()

Removes the field

Parameters:

Example:


removeField();

go to top


drawPath(name)

Draws points so you can visualize the path of an object. As if the object is dropping pixels as it moves.

Parameters:

name:string name of the object you want to have a path

Example:


drawPath('box1');

go to top


resetPath(name)

Resets the path.

Parameters:

name:string name of the object you want to reset the path

Example:


resetPath('box1');

go to top


removePath(name)

Removes the path tracking ability from the object.

Parameters:

name:string name of the object you want to remove a path

Example:


removePath('box1');

go to top


createLinePoints(name)

Creates a line that looks like individual points. You must add points to the line before it will be visible.

Parameters:

name:string name of the line you want to work with to like 'myline'

Example:

createLinePoints('myline')

go to top


createLineContinuous(name)

Creates a continuous line from the points. You must add points to the line before it will be visible.

Parameters:

name:string name of the line you want to work with to like 'myline'

Example:

createLineContinuous('myline')

go to top


createLineDiscrete(name)

Creates a line that looks like line segments between every two consecutive points. You must add points to the line before it will be visible.

Parameters:

name:string name of the line you want to work with to like 'myline'

Example:

createLineDiscrete('myline')

go to top


addPointToLine(name,x,y,z)

Adds a point to a line

Parameters:

name:string name of the line you want to add the point to like 'myline'

x,y,z:number like 0,2,0 where the next point should be.

Example:

addPointToLine('myline',0,2,0)

go to top


removeLine(name)

Test

Parameters:

name:string name of the line you want to work with like 'myline'

Example:

createLines('myline')

go to top


Experimental

colorMesh(objectname)

A proof of concept demo which changes the colors of each triangle in the list of triangles gradually changing from red to blue as it goes through the triangles

objectname:string name of the object whose mesh you want to change colors

Example:


colorMesh('box1');

go to top


Color(r,g,b,a)

Represents a color with red, green, blue, and alpha values from 0-255

Parameters:

r:number red

g:number green

b:number blue

a:number alpha

Example:


c=Color(0,0,255,255);

go to top


Working with Meshes

buildMesh(objectname)

Changes the mesh of the object. To change a mesh simply change the values of SharedVertices and SharedTriangles and then call buildMesh(). Every consecutive 3 SharedVertices is automatically turned into an x,y,z vector point with an index. For example vertices 0,1,2 below are turned into vector(0,0,0) with index 0. Each consecutive 3 SharedTriangle indexes are drawn as a triangle.

objectname:string name of the object whose mesh you want to build from triangles and vertices

Example:


//each 3 vertices will be automatically be turned into vertice vectors with an index. 

	SharedVertices[0] = 0;
	SharedVertices[1] = 0;
	SharedVertices[2] = 0;
	//the first 3 are turned into the 0 index vertice vector(0,0,0);

	SharedVertices[3] = 0;
	SharedVertices[4] = 1;
	SharedVertices[5] = 0;
	//the second 3 are turned into the 1 index vertice vector(0,1,0);


	SharedVertices[6] = 1;
	SharedVertices[7] = 1;
	SharedVertices[8] = 0;
	//the third 3 are turned into the 2 index vertice vector(1,1,0);


//this will use the 3 vertice vectors we created by index 0,1,2 to draw a triangle
	SharedTriangles[0] = 0;
	SharedTriangles[1] = 1;
	SharedTriangles[2] = 2;
	
	//replaces the box1 mesh with the SharedTriangles defined by the SharedVertices
	buildMesh('box1');
	

go to top


Text

showText(text,time)

Shows 3D text on the screen

Parameters:

text:string The text you want to show. Has some RTF features. Use \n for line break.

time:string how long in seconds you want the text to stay on the screen.

Example:

showText('You Win!','title',5);

go to top


hideText()

Shows 3D text and a visual display. Used when a goal is reached.

Parameters:

Example:

hideText();

go to top


User Interface Elements

You can make your own user interface elements with a few lines of code

Each user interface element has an internal id and title. The id is for you to keep track of the html object that contains the UI so you can change it using javascript, the title is what's seen on the screen. After a UI element has been created you can call it in javascript by id. UI elements have many properties which can be changed during runtime. If you right click -->inspect element -->go to console--> type in the id of your UI element you can see all the UI element object properties. You can change any property using standard javascript. For example to change the width of a widget object whose id is 'jump' you would write jump.style.width='200px' or you could use document.getElementById('jump').style.width='100px'

createButton(id,title,downfunction)

Creates an HTML Button which will call a function when the button is pressed.

Parameters:

name:string id of the html dom element object that contains the momentary button

title:string title

downfunction:string name of function that will be called when the button is changed to down

Example:


function jumpCow(){
	cow1.vel.y=5;
}
createButton("mybutton",'mycowjump','jumpCow');

go to top


createMomentary(id, title,downfunction, upfunction)

Creates an HTML Momentary Button which has two states up and down. When it is pressed down The downfunction is called. When you let go of the button the upfunction is called.

Parameters:

name:string id of the html dom element object that contains the toggle.

title:string title

upfunction:string name of function that will be called when the momentary button is released

downfunction:string name of function that will be called when the momentary button is pressed

Example:


function jetOn(){
	cow1.acc.y=5;
}
function jetOff(){
	cow1.acc.y=0;
}
createMomentary('mycowjetpackmomentary','off/on','jetOff','jetOn';

go to top


createToggle(id,title,downfunction,upfunction)

Creates an HTML Toggle Button which has two states up and down. The upfunction is called when the toggle is switched up, the downfunction is called when the toggle is switched down.

Parameters:

name:stringid of the html dom element object that contains the toggle.

title:string title

upfunction:string name of function that will be called when the toggle is switched up

downfunction:string name of function that will be called when the toggle is switched down

Example:

function jetOn(){
	cow1.acc.y=5;
}
function jetOff(){
	cow1.acc.y=0;
}
createToggle('mycowjetpacktoggle','on/off','jetOn','jetOff';

go to top


createSlider(id, title,functionname, low, hi, step, defaultValue,bounce)

Creates an HTML slider. The function functionname is called when the slider is changed and the value of the slider is sent to the function. You must create a function that receives the value

Parameters:

name:string id of the html dom element object that contains the slider

functionname:string name of function that will be called when the button is pressed

title:string title

low:number The low range of the slider. Will be placed on the low end of the slider

high:number The high range of the slider. Will be placed on the high end of the slider

step:number The slider range is divided by these steps

defaultValue:number The default value of the slider

bounce:true or falseDefault is false. If true when you let go of the mouse it will bounce back to the default value, does not work on Firefox

Example:


function launchCow(value){
	cow1.vel.y=value;
}
createHtmlSlider('mycowlauncher','launch','launchCow',0,10,1,5);

go to top


}

createKey(key,functionname)

Links a key to a functionname which is called when the key is pressed

Parameters:

key:string which key is linked to the function

functionname:string name of function that will be called when the key is pressed

Example:

function launchCow(){
	cow1.vel.y=10;
}
createKey('j','launchCow')

go to top


removeKey(key)

Removes a key linked to a function

Parameters:

key:key

Example:

removeKey('j')

go to top


createHtmlButton(id,title,functionname)

Creates an HTML button. The function functionname is called when the button is pressed

Parameters:

name:string id of the html dom element object that contains the html button

title:string title will be placed on the button

functionname:string name of function that will be called when the button is pressed

Example:

function launchCow(){
	cow1.vel.y=10;
}
createHtmlButton('mycowjumper','Cow Jump','launchCow')

go to top


createHtmlButtonWithInput(id, title, functionname,default)

Creates an HTML button with a user input field. The user input is send to a function when the button is pressed

Parameters:

name:string id of the html dom element object that contains the html button

title:string will be put next to the input

functionname:string name of function that will be called with the input parameter

Example:


function setGravity(frominput){
		penguin1.acc.y=frominput;
}
createHtmlButtonWithInput('mygravityinput','G-Force','setGravity',-9.81)

go to top


createHtmlTextarea(id,text notimplemented yet fixthis)

Creates an HTML textarea

Parameters:

name:string id of the html dom element object that contains the html button

text:string will be put in the textarea

Example:

createHtmlTextarea('userinput','Type your solution here:')

go to top


createImage(name,src)

Creates HTML Image

Parameters:

name:string id of the html dom element object that contains the image.

src:string The source references an images stored somewhere on the internet. It could be an image you've uploaded to a server. Or you could use a service like imgur to upload an image

Example:

createHtmlImage('einstein','http://www.cinematicsciences.com/images/einstein.jpg');

go to top


createTitle(id,txt)

Creates HTML Text

Parameters:

name:string id of the html dom element object that contains the title

txt:string

Example:

createHtmlTitle('gravitytitle','Gravity Changer')

go to top


createText(id,text)

Creates HTML Text

Parameters:

name:string id of the html dom element object that contains the text

text:string

Example:

createHtmlText('gravitydescription','This allows you to change the gravity.')

go to top


createSelect(id,title,functionname change to func not implemented yet fixthis,optionarray,defaultoption)

Create a standard html select

Parameters:

name:string id of the html dom element object that contains the select

functionname:string name of a function that takes a string parameter that will be called when someone makes a selection

title:string title

optionarray:array A javascript string array of options

defaultoption:string The option you want to be the default option

Example:

createHtmlSelect('gravityselect','gravity',new Array('moon','earth','jupiter','blackhole'),'earth')

go to top


createMeter(id,title,watch,howoften)

Starts a meter that watches something every howoften milliseconds.

Parameters:

id:string id of the html dom element object that contains the meter

title:string title

watch:string like 'cow.vel.y' which will be put in the meter

howoften:number in milliseconds which is how often you want to put points on the chart

Example:

createMeter('mymeter','cow.pos.y',5000);

go to top


createPoints(id,title, xpoint,ypoint,howoften)

Starts listing points of whatever is in xpoint and ypoint every howoften milliseconds.

Parameters:

id:string id of the html dom element object that contains the points

title:string title

xpoint:string like 'cow.pos.x' to be put in the x column

ypoint:string like 'cow.pos.y' to be put in the y column

howoften:number in milliseconds which is how often you want to put points on the chart

Example:

createPoints('mypoints','cow.pos.x','cow.pos.y',1000);

go to top


createChart(id,title,xpoint,ypoint,howoften,
xlow,xhigh,xdivs,ylow,yhigh,ydivs)

Starts a Chart of whatever is in xpoint and ypoint every howoften milliseconds.

Parameters:

id:string id of the html dom element object that contains the chart

title:string title

xpoint:string like 'cow.pos.x' to be put on the x axis

ypoint:string like 'cow.pos.y' to be put on the y axis

howoften:number in milliseconds which is how often you want to put points on the chart

xlow:number lowest range of x-axis

xhigh:number highest range of x-axisyou want to put points on the chart

xdivs:number divisions between xlow and xhigh on x-axis

ylow:number lowest range of y-axis

yhigh:number highest range of y-axis

ydivs:number divisions between ylow and yhigh on y axis

Example:


createChart('mychart','cow.pos.x','cow.pos.y',5000,0,100,10,0,100,10);
//creates a chart which updates every 5 seconds
//has a x-axis range of 0 to 100 in 10 divisions
//has a y-axis range of 0 to 100 in 10 divisions

go to top


AddCommandLine()

Creates a Command Line input and button.

Parameters:

Example:


AddCommandLine();

go to top


CreateHelp(id,title,content)

Creates a help button which pops up helpful information.

Parameters:

id:stringid of the html dom element object that contains the help

title:string title

content:html helpful information in html format

Example:


createHelp('help1','instructions','Instructions
Push the right button to go right
Push the left button to go left');

go to top


Positioning User Interface Items

You can move UI elements around using moveUI() and fixUI() functions. You can save the positions of your UI elements by pasting in the code that is produced by fixUI() after the controls are created.

User Experience Design: Goals, Rewards, Quizzes, Surveys

showPage(url)

Shows any webpage that you've made and that exists on a server or service. Could be an instructions page, a quiz page, or a survey page. The webpage will cover the editor and debugger.

Parameters:

url:string url address of the web page

Example:


showPage('http://www.cinematicsciences.com/instructions.html');
showPage('http://www.surveymonkey.com/quiz.html');
showPage('http://www.surveymonkey.com/survey.html');

go to top


hidePage()

Hides the page

Parameters:

none

Example:

hidePage();

go to top


Setting Goals for Students

setGoal(func,time)

Sets a goal for the user

Parameters:

func:string name of the function that checks the goal

time:number How often in milliseconds that you want to check to see if the goal has been reached 1000 milliseconds = 1 second

Example:


//In this example the reward is given while the goal is true. First create a function that checks the goal and gives a reward for reaching the goal. Note this example rewards the user multiple times if the goal condition is still true.
function goalcheck(){
//you give a reward if something is true
if(box1.pos.y>10){
//rewards
showText('you reached the goal','title',5);
coins=coins+100;//add 100 to coins
youWin(10,'goldcoin','box1','You just earned 100 coins');//visual effect
showPage('http://www.secreturl.com');//change page frame
saveSolution();//Offer the user the chance to save their solution.
}
}
setGoal('goalcheck',1000);

//In this example the reward is given only the first time the condition is true, not every time. First create a function that checks the goal and gives a reward for reaching the goal
var reward=false;//We use a global reward variable to check whether the reward was given or not.
function goalcheck(){
if(reward==false && box1.pos.y>10){
//rewards
showText('you reached the goal','title',5);
coins=coins+100;//add 100 to coins
youWin(10,'goldcoin','box1','You just earned 100 coins');//visual effect
showPage('http://www.secreturl.com');//change page frame
saveSolution();//Offer the user the chance to save their solution.
reward=true;//set to true so no more rewards are given.
}
}
setGoal('goalcheck',1000);

go to top


deleteGoal(func)

Deletes a goal by the function name provided when you created the goal.

Parameters:

func:string function name of the goal

Example:

deleteGoal('mygoal');

go to top


deleteAllGoals()

Deletes all Goals

Parameters:

none

Example:

deleteAllGoals();

go to top


youWin(type,text,func)

Shows a text message and releases a number of of a type of object like coins above the target. Use when a goal is reached.

Parameters:

param:numbernumber of objects to release

type:string object type like goldcoin,box

target:string Object name where you want the coins to be released

text:string text you want to show.

Example:


youWin(10,'goldcoin','penguin','You just earned 100 coins');

go to top


Global Variables

There are a few variables that keep track of objects and other variables

objects :array accessed by a number all loaded objects are stored in the objects variable. You can refer to each object by the number order it was loaded starting with 0

Example:


//once you've loaded an object it is stored in the objects variable in order of loading
load('box','box1');
load('box','box2');
//box1 goes in objects[0] 
//box2 goes in objects[1] in order of loading.
objects[0].name; //is box1
objects[1].name; //is box2

go to top


cs :array of all objects and variables accessed by a name all loaded objects and variables are stored in the cs variable. You can refer to these by name.

Example:


load('box','box1');
cs['box1'].name; //is equivalent to box1 

go to top


More Examples:


//see the for loop section for examples of using these global variables to build stacks of blocks.

go to top


find(name)

Sometimes you need to find an object using it's name instead of directly calling it's object. You can use find for that.

name:string a name like 'box1','penguin1','jonathan'

find('penguin');//is equivalent to typing penguin
find('box1').pos.y=10;//is equivalent to box1.pos.y=10;
find('box'+1).pos.y=10;//is equivalent to box1.pos.y=10;
//an example of using a for loop and find to change the pos.y of 10 boxes
for(var i=0;i<10;i++){
  find('box'+i).setPosition(0,i*2,0);
}

go to top


Vectors and Rotation Math

vector(x,y,z)

To position something we use a vector. A vector holds numbers for each dimension in space. In 3D we use x,y,z. The positive x direction is to the right. The positive y direction is up and the positive z direction is out of the page.

x:number
y:number
z:number

var v=vector(1,2,3);
box1.pos=vector(0,0,0);

go to top




//vector functions
function distance(vec1,vec2){
    var x=vec1.x, y=vec1.y, z=vec1.z;
    var x1=vec2.x,y1=vec2.y,z1=vec2.z;
    
    return Math.sqrt((x1-x)*(x1-x)+
                     (y1-y)*(y1-y)+
                     (z1-z)*(z1-z));
};

function addVec(vec1,vec2){
	vec=vector(vec1.x+vec2.x,vec1.y+vec2.y,vec1.z+vec2.x);
	return vec;
}

function subtractVec(vec1,vec2){
	vec=vector(vec1.x-vec2.x,vec1.y-vec2.y,vec1.z-vec2.z);
	return vec;
}

function multiplyVec(vec1,n){
	vec=vector(vec1.x*n,vec1.y*n,vec1.z*n);
	return vec;
}

//more quaternion and functions are available in quaternion.js
//Copyright (c) 2017, Robert Eisele Dual licensed under the MIT or GPL Version 2 licenses.
//the source is located at whimsica.com/quaternion.js or the current url/quaternion.js
//quaternion.js has not been altered in any way.

//note you may have to convert our vector and rotation format into quaternion.js vector
//before using the quaterion.js functions.
//feel free to use your own math library see the section: Integrate another javascript library into your project:

setRotationType(string)

Set the rotation type to euler or quaternion. Eulers are traditional vectors with x,y,z rotations. Asking for the current euler rotation can give back unpredictable results because there is more than one way to describe a rotation using x,y,z. Quaternions have 4 parameters: x,y,z,w and are more reliable for advanced rotation mathematics. You can use one or the other but not both at the same time. The default is Euler Angle Rotations

string:euler/quaternion euler or quaternion

Example:


setRotationType('euler');

go to top


eulerToQuaternion(vector)

Convert an euler vector rotation into a quaternion.

vector:vector vector with x,y,z components

Example:


vec=new vector(0,90,0);
var newquat=eulerToQuaternion(vec);
console.log(newquat);

go to top


quaternionToEuler(Rotation)

Convert an euler vector rotation into a quaternion.

Rotation:Rotation rotation with x,y,z,w components

Example:


rot=new Rotation(0,0,0,1);
var newEuler=quaternionToEuler(rot);
console.log(newEuler);
//Note CS uses a simple Vector4 called Rotation. If you are using a mathematics package that has quaternions that are not simple vector4's -- some are objects with multiple properties, then you'll have to take the x,y,z,w components and assign them to a CS Rotation. 
quat=Quaternion from some mathematics package that does not use a simple Vector4 structure;
newrot=Rotation(quat.x,quat.y,quat.z,quat.w);

go to top


Integrate another javascript library into your project

Example:


addScript('http://www.someserver.com/somecode.js');//The location has to be on a server somewhere and the file type has to be .js. 

//addScript only works with .js files. Many C and C++ libraries can be converted into .wasm webassembly libraries with Emscripten.  To use .wasm libraries you will need to add webassembly loading code at the beginning of your script.

go to top


Interactive Fiction Programming

Interactive Fiction Programming is not implemented yet but you can see the source code in jag2081.js. To start up the interactive fiction module run startJag();



Javascript Programming Basics

Before you start programming in Cinematic Sciences you need to learn the language that the computer speaks. In Cinematic Sciences the computer speaks JavaScript.

This is a quick lesson in JavaScript.
You can paste the code into the CS editor and press run to see what it does.

Comments

When you see two slashes // in front of a line the computer will treat the line as a comment and ignore it.
Programmers use comments to ignore lines of code and to help remind themselves how to understand the code.


//the first load function will not run because it is ignored as a comment.
//load("penguin","peng");
load("penguin","peng");

Variables:

Variables are like boxes that you store stuff in.

Example:

var mybox=5;

Here's a variable called mybox that I put the number 5 in it. The computer puts whatever is on the right side of the = into the variable.

In JavaScript = does not mean mathematical equals.
In JavaScript x=5 is an instruction that says put 5 into x

We can also put text into variables. In computer science text is called a string. You can think of it like letters connected by a string like this: H-e-l-l-o--W-o-r-l-d. A string is is always in quotes.Here is an example of a string variable:

Example:

var mystring= 'Hello world!';

go to top


Outputs

To see what's in a variable you can use alert or log or console.log. Alert pops up a box on the screen, log writes the output to the debugger, console.log writes to the browser console. You can look up online how to open up the console.log for your browser.

Example:


alert(mybox);
//will output 5
log(mystring);
//will output 'Hello world!'

go to top


You can mix strings with variables in an alert statement using the '+' symbol

Example:


var mybox=5;
alert(mystring +' I have ' + mybox + ' cents');
//will output 'Hello World! I have 5 cents');

go to top


Arrays

You can store a list of things in a variable. In JavaScript a list is called an Array. Here are some arrays.

Example:


var mynumbers=new Array(1,2,3,4,5);
var myslangWords=new Array('cool','chill','hot doggy');
var myintroductions=new Array('Hi!','Wassup','Yo');

go to top


To get an item from an array you use a number in brackets like this [2].

Example:


var mynumbers=new Array(0,1,2,3,4,5);
alert(mynumbers[2]);
//will output: 2
//Note arrays count from 0 not from 1 [0] is the first item in the array [1] is the second item.
//if you are having problems with your arrays you may not be counting from 0.

go to top


To put an item in an array you just tell where to put it with a number in brackets like this [8].

Example:


var numbers=new Array(0,1,2,3,4,5);
numbers[8]=1000;
alert(numbers);
//will output: 0,1,2,3,4,5,,,1000;

go to top


An Array can be filled with objects strings,numbers, or even other arrays.You can add items to an array and remove items from the array. Or you can look through it using a which is discussed below

Objects

You can also store an Object in a variable. An Object is something that has properties. Wheverer the object goes the properties go with it. Each property is linked to the object with a '.'

Example:


mycar=new Object();
mycar.wheels=4;
mycar.color='blue';
mycar.model='Porsche';
mycar.owner='me';

go to top


To output the color of car you can use an Alert or send it to the log using log. Alert and log are used to see what's in a variable.

Example:


alert(mycar.color);
//will output 'blue'
log(mycar.owner);
//will output 'me'

go to top


if then else

An if then else statement tests whether or not something is true, called a condition, then does something if it is. For example if the condition is that it's a school day, then you go to school, else you go play. Here are some examples:

Example:


var mydice=6;
if(mydice>4){
	alert('You Win')
}
else{
	alert('You Lose');
}
//outputs 'You Win';
 

go to top


Example:


var name='fred';
if(name=='fred'){
	alert('Hi Fred');
}
else{
	alert('I don't know you');
}
}
//outputs 'Hi Fred'
 

go to top


Example:


var classmates=new Array('joe','moe','robert');
if(classmates[0]=='joe'){
	alert('Yo Joe!')
}
//outputs Yo Joe!
 

go to top


Example:



var car=new Object();
car.color=blue;
car.owner='rob';
}
if(car.owner=='rob'){
	alert(car.owner + ' owns the ' + car.color + ' car')
}
//output rob owns the blue car
 

go to top


Note: To test whether or not something is true you can use equals ==, not equals !=, greater than >, and less than <. You can also string together if statements with the symbols && for And, and || for Or.

Example:


var dice1=5;
var dice2=2;
if(dice1==5&&dice2==2){
	alert('You rolled a 7')
}
//output You rolled a 7
 

go to top


For loop

A for loop will run the code inside the loop brackets {} according to the 3 rules in the parantheses (). The rules include where to start, when to end, and how to count. For loops are often used to check every item in an array, or do something to every item in an array.

Example:


for(var i=0;i<10;i++){
	alert(i);
}

go to top


The for loop controls have 3 parts separated by a ';'

The JavaScript for loop structure will run any code inside the loop brackets according to the for loop controls.

More Examples:


//load a stack of boxes using the global variable named objects
for(var i=1;i<10;i++){ load('box','box'+i);
objects[i].ontop(objects[i-1]);
}
//load a stack of boxes using the global variable cs
for(var i=1;i<10;i++){
load('box','box'+i);
n=i-1;
cs['box'+i].ontop(cs['box'+n]);
}

//load a stack of boxes using your own array named boxes
boxes=new Array();
for(var i=1;i<10;i++){
load('box','box'+i);//stored in objects
boxes[i]=objects[i];
boxes[i].ontop(boxes[i-1]);
}

go to top


A while will loop will run whatever is inside as long as the condition statement is true

Example:


while(cow.animation=='eat'){
	log('the cow is eating');
}

go to top


Functions

A function is like a set of instructions that you would give to someone to tell them how to do something. For Example: Brush your teeth. If you put it on paper it might look something like this: First get toothpaste, put it on the toothbrush,open your mouth, Put the toothbrush in your mouth, move the toothbrush around on your teeth, spit out the toothpaste, rinse your mouth with water. Put the toothbrush down. In JavaScript this would look like this

Example:


function brushTeeth(){
	getToothpaste
	PutToothpasteOnToothbrush
	OpenMouth
	etc...
}	

go to top


To call the function in JavaScript you would just write the name of the function and add () to the end.

Example:


brushTeeth();

go to top


Functions make it easy to tell the computer to do long lists of instructions. Here's a real JavaScript function that multiplies two numbers together

Example:


function multiply(){
	var a=5;
	var b=5;
	alert(a*b);
}
multiply();//you have to call the function to run it.

go to top


Functions can take in information and use it. The () in front of the function can be filled with variables separated by commas. You can send information into these variables when you call the function. The function can then do different things depending on the information that is sent into the variables. For example:

Example:


function multiply(a,b){
	alert(a*b);
}
multiply(3,5);//you have to call the function to run it.

go to top


A function with if else:


function givePromotion(name,age,rank){
	if(rank=='level0'&&age>20){
	alert(name + ' gets a promotion!');
	}
	else{
	alert('Sorry '+name + ' does not get a promotion.');
	}
}
givePromotion('Katherine',22,'level0');
//output Katherine gets a promotion!
givePromotion('David',18,'recruit');
//output David does not get a promotion.

go to top


A function with an array and a for loop


function inClass(studentname){
myClass=new Array('Jameel','Walter','Katherine');
//loop through all the students
for(var i=0;i< myClass.length;i++){
	//loop through the array to see if each students is in the class
if(myClass[i]==studentname){
alert(studentname+' is in the class!');
}
}
}
inClass('Katherine');//output: Katherine is in the class!

go to top


Functions can return values. A function with the word return in it will return whatever is after the return. For example:

Example:


function add(a,b){
return a+b;
}
var answer=add(3,5);//will return 8 and put it into the answer variable
alert(answer);
//output answer=8

go to top


Problems and Troubleshooting

When your script has code that the computer cannot understand the debugger will show the error. The Debugger is located below the editor.

The debugger will try to tell you what it thinks the error is and also what line it is on. The debugger is not perfect. Think of the debugger is giving you clues to solve the mystery of what's wrong with your code, but it may be slightly or majorly wrong about the location. If it says there is an error on line 20, also look around on line 19 and 21 also. If it says the error is on line 1 and you don't see an error on Line 1 Look for missing () {} and '' anywhere on the page. Then look for words that are not quite right like 'box' when it should be 'box1'. Sometimes the debugger will say something cryptic -- you can always look up that error on google or stack-overflow for a better explanation of the error.

The debugger is just one way to see what's wrong with your code. Another way is to open the console log on your browser. I do this by right clicking on anything on the screen then going to inspect element and then choosing 'console' This brings up a whole panel for developers. If you find the word console and click on it, it will have every error that the entire program is making not just your code. This may give you clues also. You are looking for syntax errors. At the bottom of the console is place where you can type. If you type in a variable name it will show you all the properties of that variable. You can also type in javascript. For advanced users you can see and change properties. Start typing top.webgliframe. For example if have an object named penguin it would be top.webgliframe.penguin. to see all the properties and variables that penguin has. If you have created a button named button1 you would use top.webgliframe.button1 to see all the properties.

A common error is An abnormal situation has occurred: the PlayerLoop internal function has been called recursively.
Restart the page using the restart button on the page across from the docs tab. If that doesn't work you'll have to refresh the page itself. If that doesn't work you'll have to quit the browser and start it up again.

For loops and while loops that never end can hang your browser. If your browser stops responding there is something in your code that is running and won't stop. Refresh the page and check the stop conditions on your for loops and while loops. Another thing that can cause an infinite loop is a function which calls another function which calls the original function, or a function that calls itself.

If your project seems to be choppy, remove unnecessary log() or console.log() calls. These can slow down the browser. Comment them out and see if the project runs more smoothly.

If your program is frozen or unresponsive see if one of these will fix the problem:

  1. So you don't lose your work, copy your script by selecting it and going to edit-copy. Paste your script somewhere on your computer so you have a copy of it.
  2. Hit the restart button to the right of the About tab.
  3. Find the refresh button for the browser that will reload the page. Google if you're not sure where it is.
  4. Close the browser window.
  5. Quit the browser and start it up again.
  6. Clear the history and cache of the browser. Google if you are not sure how to do this.
  7. Force the Browser to Quit
  8. Post your code and ask a question about why it doesn't work on StackOverflow.com

Tutorials

Tutorial Link Test

This section is not working yet. Tutorial links coming soon

Here you go step1 of the Build a game tutorial

Here you go step2 of the Build a game tutorial


//hit run to start
//then hit instructions
//then hack the code

//load objects
load('penguin','penguin',-5,1,0);

//create tower
load('box','box0');//start box
box0.scale=vector(2,2,2);

//loop to add 9 more boxes 
for(var i=1;i<10;i++){
load('box','box'+i);
find('box'+i).scale=vector(2,2,2);
ontop('box'+i,'box'+(i-1));//calculation (i-1) must be in parenthesis
find('box'+i).rot.v=vector(0,0,0);
}

//cameras
setCamera('penguin','follow',50,0,1,20);
dynamicZoomOn('penguin','box9');

//user interface
createHelp("myhelp","instructions","Drag the penguin's hands legs or feet and try to land on top of the stack of blocks for 10 seconds.")
createHelp("myhelp","instructions 2","Can you knock out only the bottom block? 
You can change physics by typing code into the command line.
For example: penguin.mass=10;
box0.setFriction(1)
box0.mass=2
See the docs-->physics for more info.") startTimer("yvel");//this should to be in place before we create the chart createButton('myreset','reset','clearRun()'); //createChart to be last due to some mywidget bug createChart("vel","velocity","getTimer('yvel')/500","penguin.vel.y",500,0,100,10,-20,20,5) //functions function reset(){ checkstacktimer=0; createInterval('checkStack',1000); box0.pos=vector(0,1,0); box0.vel=vector(0,0,0); box0.angvel=vector(0,0,0); for(var i=1;i<10;i++){ find('box'+i).rot=vector(0,0,0); find('box'+i).vel=vector(0,0,0); find('box'+(i-1)).rot=vector(0,0,0); ontop('box'+i,'box'+(i-1)); } penguin.pos=vector(-5,1,0); penguin.vel=vector(0,0,0); } createInterval('checkLanding',1000); collisionWatch('penguin','box9','onEnter','onExit'); landedTimer=0; landed=false; function onEnter(){ landed=true; //log('landed'); } function onExit(){ landed=false; landedTimer=0; //log('left'); } function checkLanding(){ if(landed==true){ landedTimer+=1; } if(landedTimer==10){ youWin(10,'goldcoin','penguin','You just earned 10 coins');//visual effect showText("You Win",5,"bold"); } //log('landedTimer='+landedTimer); } //extras //to measure acceleration we don't use object.acc because that is what is applied //to the object each frame. //instead we have to actually measure the change in velocity over time. //pVy=0; //var measuredacc=0; //createInterval("getAcc",250); //function getAcc(){ // vy1=penguin.vel.y; // measuredacc=vy1-pVy; // measuredacc=measuredacc*1000/250;//the denominator is the interval rate // pVy=vy1; // log(measuredacc); //} //startTimer("yvel"); //createChart("vel","acceleration","getTimer('yvel')/500","measuredacc",500,0,100,10,-20,20,5)

go to top