Tutorials, extensions, and source files for ActionScript, Flash, and other Adobe products.

 

senocular.com ActionScript Library

SeekProjectile.as

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.senocular.gyro {
	
	import flash.geom.Point;
	/**
	 * Seekers follow target at a constant acceleration
	
	TODO: option for constant vector acceleration for x/y instead of individually
	option for matching if lower? do automatically?
	 */
	public class SeekProjectile extends Seek {
		
		protected var _acceleration:Number = .5;
		protected var _orient:Boolean = true;
		protected var vector:Point = new Point(0, 0);
		
		private static const TO_DEGREES:Number = (180/Math.PI);
		
		/**
		 * A value between 0 and 1 representing how quickly
		 * a seeker accelerationes the target with every step
		 */
		public function get acceleration():Number {
			return _acceleration;
		}
		public function set acceleration(n:Number):void {
			_acceleration = n;
		}
		
		/**
		 * When true, rotation is set to point to the target
		 */
		public function get orient():Boolean {
			return _orient;
		}
		public function set orient(b:Boolean):void {
			_orient = b;
		}
	
		/**
		 * Constructor
		 */
		public function SeekProjectile(acceleration:Number = .5, orient:Boolean = true){
			super([]);
			this.acceleration = acceleration;
			this.orient = orient;
		}
		
		/**
		 * Seek method; matches seeker properties
		 * to target properties based on the properties list
		 */
		public override function follow(target:*, seeker:*):void {
			if (!_acceleration) return;
			var dx:Number = target.x - seeker.x;
			var dy:Number = target.y - seeker.y;
			var dist:Number = Math.sqrt(dx*dx + dy*dy);
			var angle:Number = Math.atan2(dy, dx);
			
			if (_orient) {
				seeker.rotation = angle*TO_DEGREES; 
			}
			
			vector.x += _acceleration * Math.cos(angle);
			vector.y += _acceleration * Math.sin(angle);
			
			seeker.x += vector.x;
			seeker.y += vector.y;
		}
	}
}