github.com/atsaki/terraform@v0.4.3-0.20150919165407-25bba5967654/website/source/assets/javascripts/app/Puller.js (about) 1 (function( 2 Engine, 3 Vector 4 ){ 5 6 var Puller = function(x, y){ 7 this.pos.x = x; 8 this.pos.y = y; 9 this.pos = Vector.coerce(this.pos); 10 this.home = this.pos.clone(); 11 this.accel = Vector.coerce(this.accel); 12 this.vel = Vector.coerce(this.vel); 13 }; 14 15 Puller.prototype = { 16 17 fillStyle: '#ffffff', 18 radius: 5, 19 20 maxSpeed: 160, 21 maxForce: 50, 22 23 pos: { 24 x: 0, 25 y: 0 26 }, 27 28 accel: { 29 x: 0, 30 y: 0 31 }, 32 33 vel: { 34 x: 0, 35 y: 0 36 }, 37 38 aRad: 200, 39 40 safety: 0.25, 41 42 update: function(engine){ 43 var distanceToMouse = this.distanceTo(engine.mouse), 44 toHome, mag, safety; 45 // distanceToHome = this.distanceTo(this.home); 46 47 this.accel.mult(0); 48 49 if (distanceToMouse < this.aRad) { 50 this.toChase(engine.mouse); 51 } 52 53 this.toChase(this.home, this.maxForce / 2); 54 55 this.vel.add(this.accel); 56 this.pos.add( 57 Vector.mult(this.vel, engine.tick) 58 ); 59 60 toHome = Vector.sub(this.home, this.pos); 61 mag = toHome.mag(); 62 safety = this.aRad * (this.safety * 3); 63 if (mag > this.aRad - safety) { 64 toHome.normalize(); 65 toHome.mult(this.aRad - safety); 66 this.pos = Vector.sub(this.home, toHome); 67 } 68 }, 69 70 toChase: function(target, maxForce){ 71 var desired, steer, distance, mult, safety; 72 73 maxForce = maxForce || this.maxForce; 74 75 target = Vector.coerce(target); 76 desired = Vector.sub(target, this.pos); 77 distance = desired.mag(); 78 desired.normalize(); 79 80 safety = this.aRad * this.safety; 81 82 if (distance < safety) { 83 mult = Engine.map(distance, 0, safety, 0, this.maxSpeed); 84 } else if (distance > this.aRad - safety){ 85 mult = Engine.map(this.aRad - distance, 0, safety, 0, this.maxSpeed); 86 } else { 87 mult = this.maxSpeed; 88 } 89 90 desired.mult(mult); 91 92 steer = Vector.sub(desired, this.vel); 93 steer.limit(maxForce); 94 this.accel.add(steer); 95 }, 96 97 draw: function(ctx, scale){ 98 // ctx.beginPath(); 99 // ctx.arc( 100 // this.home.x * scale, 101 // this.home.y * scale, 102 // this.aRad * scale, 103 // 0, 104 // Math.PI * 2, 105 // false 106 // ); 107 // ctx.fillStyle = 'rgba(255,255,255,0.1)'; 108 // ctx.fill(); 109 110 ctx.beginPath(); 111 ctx.arc( 112 this.pos.x * scale, 113 this.pos.y * scale, 114 this.radius * scale, 115 0, 116 Math.PI * 2, 117 false 118 ); 119 ctx.fillStyle = this.fillStyle; 120 ctx.fill(); 121 122 }, 123 124 distanceTo: function(target) { 125 var xd = this.home.x - target.x; 126 var yd = this.home.y - target.y; 127 return Math.sqrt(xd * xd + yd * yd ); 128 } 129 }; 130 131 window.Puller = Puller; 132 133 })( 134 window.Engine, 135 window.Vector 136 );