Behaviors - norybiak/AltspaceSDK-wiki GitHub Wiki
##What are behaviors? Behaviors are functions that make objects do stuff. It's a pattern that promotes cleaner and reusable code.
##Basic layout
Start, update, and config are optional. Awake is technically optional too, but without awake you won't have easy access to the object3d.
function MyBehavior(config)
{
var config = config || null;
var object3d;
function awake(o)
{
object3d = o;
}
function start()
{
}
function update()
{
}
//only return what you need to be exposed. If you don't use start or update, don't return it.
return { awake: awake, start: start, update: update };
}
##Core functions
###function awake(o) Awake is called before start and update.
Notice that awake is given o. o in this case is the object3D in which the behavior is attached to. You can name o to whatever you want, but it's better to create a variable called object3d and assign o to it (based on the basic layout above).
Example:
function awake(o)
{
object3d = o;
otherVar = otherStuff;
runFunction();
}
###function start() Start is called after awake and before update.
Example:
function start()
{
//All initialization is done, run the important functions that depended on the init.
}
###function update() Update is called on every frame after awake and start have finished working.
Example:
function start(optionalParam)
{
//this will move the object 0.001 units on y (upwards).
object3d.position.y += 0.001;
}
##Other functions You can create other functions within the behavior that support the core functions and any config options. You can see an example below (getVec3FromString(str)). #Example This example uses oOblik's native component library
/*
* Behavior: DebugPosition
* Description: Create text on the cockpit that shows the x,y,z coordinates of the object3d
* Config: textPosition - the position of the debug text on the cockpit
*
* Usage: object3d.addBehavior(DebugPosition({textPosition: '0 0 0'}));
*/
function DebugPosition(config)
{
var config = config || null;
var pos = getVec3FromString(config.textPosition);
var object3d;
var debugText, cockpitParent;
function getVec3FromString(str)
{
if (str !== undefined)
{
var params = str.split(' ');
return new THREE.Vector3(params[0], params[1], params[2]);
}
else
{
return new THREE.Vector3(0, 0, 0);
}
}
function awake(o)
{
object3d = o;
debugText = new NativeComponent("n-text", { text: ' ' });
debugText.object.position.copy(pos);
cockpitParent = new NativeComponent('n-cockpit-parent', null, debugText.object).addTo(sim.scene);
}
function update(deltaTime)
{
var str = 'X: ' + object3d.position.x + 'Y: ' + object3d.position.y + 'Z: ' + object3d.position.z;
debugText.update({text: str});
}
return { awake: awake, update: update };
};