package com.sarmatianHeroes.objects 
{
	import flash.display.*;
	import flash.events.*;
	
	import com.antkarlov.math.*;
	
	public class Arrow extends MovieClip
	{
		//g is constant
		//it's actually closer to 10 but this is our world
		public static const g:Number = 0.2;
	
		//our arrow
		private var arrow:Shape;
	
		//start velocities
		private var ux:Number;
		private var uy:Number;
		private var targetY:Number;
		private var targetX:Number;
		private var distX:Number;
		public var Damage:Number;
		var _targetA;
	
		public function Arrow()
		{
			/*arrow = new Shape();
			arrow.graphics.lineStyle( 1, 0 );
			arrow.graphics.lineTo( 20, 0 );*/
		}
	
		public function fire(target:Object):void //tx:Number, ty:Number
		{
			if(target is Squad)
			{
				var _hero:HeroBow = new HeroBow;
				Damage = _hero.Damage;
				_hero = null;
				_targetA = target as Squad;
			}
			else if(target is HeroBase)
			{
				var _sq:SquadBow = new SquadBow("HazarBow",1);
				Damage = _sq.Damage;
				_sq = null;
				_targetA = target as HeroBase;
			}
			targetY = target.y+Amath.random(-30, 30);
			targetX = target.x;
			distX = (targetX-x);
			var radian:Number=Math.atan2(targetY-y,targetX-x)-Math.PI/8*distX/400;
			var s:Number=9;
			var vy:Number=Math.sin(radian)*s;
			var vx:Number=Math.cos(radian)*s;
			ux = vx;
			uy = vy;
			//addChild( arrow );
			addEventListener( Event.ENTER_FRAME, fly );
		}
	
		private function fly( e:Event ):void
		{
			//if(Math.abs(targetY - y)< 20 && Math.abs(targetX - x)< 20 || y > 600 || x < 0 || x > 800)
			
			if(this.hitTestObject(_targetA) || y > 600 || x < 0 || x > 800)
			{
				removeEventListener( Event.ENTER_FRAME, fly );
				parent.removeChild(this);
				if(_targetA.quantity > 0)
				{
					trace(_targetA);
					_targetA.takeDamage(Damage);
				}
				
			}
			else
			{
				//lets use our equations
				var sx:Number = ux;       //distance moved in x dir
		
				var vy:Number = uy + g    //new velocity in y dir
				var sy:Number = uy + g/2  //distance moved in y dir
		
				//apply to arrow
				x += sx;
				y += sy;
		
				//save new y velocity
				uy = vy;
				x += ux;
				y += uy;
		
				//extra bonus rotation of arrow to point in the right direction
				this.rotation = Math.atan2( uy, ux ) * 180 / Math.PI;
			}
		}
	}
}
