Add behaviors at run time

How to add a behavior after creating an object

Behaviors can be added and removed at any time using SceneObject.addBehavior() and SceneObject.removeBehavior().
// define a behavior function MoveToMouse = function() { this.onMouseMove = function(eventData) { this.owner.moveTo(eventData.screenPosition.x, eventData.screenPosition.y, 250); }; }; App = function() { this.init = function() { // create a text object that uses our TestBehavior var textSprite = new TextSprite('Click here to add behavior', '32px Arial', 'red', 'center'); var textObject = new SceneObject(textSprite); textObject.onMouseDown = function() { // add a MoveToMouse behavior if not present already if (!this.getBehavior()) { this.addBehavior(MoveToMouse); textSprite.setText('Now move your mouse'); } }; // add the object to the scene wade.addSceneObject(textObject, true); // make it listen for global mouse events wade.addGlobalEventListener(textObject, 'onMouseMove'); }; };
Your code was executed successfully!