1 // Load all required engine components 2 R.Engine.define({ 3 "class":"R.components.logic.behaviors.Wander", 4 "requires":[ 5 "R.components.logic.behaviors.BaseBehavior" 6 ] 7 }); 8 9 // Add behavior options 10 if (R.Engine.options.behaviors === undefined) { 11 R.Engine.options.behaviors = {}; 12 } 13 14 $.extend(R.Engine.options.behaviors, { 15 "wanderChange":1, 16 "wanderRadius":30 17 }); 18 19 /** 20 * @class The wander behavior for the vehicle. Causes the vehicle to randomly move 21 * from left to right. 22 * @param amount The amount to wander in either direction 23 * @param max The maximum amount of wander that can be applied in either direction 24 * @extends R.components.logic.behaviors.BaseBehavior 25 * @constructor 26 */ 27 R.components.logic.behaviors.Wander = function () { 28 "use strict"; 29 return R.components.logic.behaviors.BaseBehavior.extend(/** @scope R.components.logic.behaviors.Wander.prototype */{ 30 31 wanderChange:0, 32 wanderAngle:0, 33 radius:0, 34 35 /** @private */ 36 constructor:function (amount, max) { 37 this.base("wander"); 38 this.wanderChange = amount || R.Engine.options.behaviors.wanderChange; 39 this.wanderAngle = 0; 40 this.radius = max || R.Engine.options.behaviors.wanderRadius; 41 }, 42 43 /** 44 * This method is called by the game object to run the component, 45 * updating its state. 46 * 47 * @param renderContext {R.rendercontexts.AbstractRenderContext} The context the component will render within. 48 * @param time {Number} The global engine time 49 * @param dt {Number} The delta between the world time and the last time the world was updated 50 * in milliseconds. 51 */ 52 execute:function (time, dt) { 53 // Adjust the current direction of travel a little bit 54 // each execution to create a wandering effect 55 var gO = this.getGameObject(), mC = this.getTransformComponent(), pt = R.clone(gO.getPosition()).add(gO.getOrigin), 56 wForce = R.clone(R.math.Vector2D.ZERO), 57 cMiddle = R.clone(mC.getVelocity()).normalize().mul(this.radius); 58 59 wForce.setLen(mC.getMaxSpeed()); 60 wForce.setAngle(this.wanderAngle); 61 62 this.wanderAngle += Math.random() * this.wanderChange - this.wanderChange * 0.5; 63 var force = R.clone(cMiddle.add(wForce)); 64 cMiddle.destroy(); 65 return force; 66 } 67 68 }, /** @scope R.components.logic.behaviors.Wander.prototype */{ 69 getClassName:function () { 70 return "R.components.logic.behaviors.Wander"; 71 } 72 }); 73 }; 74