#Library "Verifying the speed of man shot by space"
#Include "ZCommon.acs"

// ----------------------------------------------------------------------------
//
// Player view guided missile script
//
// Written by KeksDose for Russian Overkill
// Please do use and modify this script as you wish, but please keep the source
// file with this comment section intact and credit me somewhere.
//
// ----------------------------------------------------------------------------

#LibDefine DEBUG			FALSE	// Enable debug messages?
#LibDefine GM_TURNSPEED		0.013	// Both vertical and horizontal
#LibDefine GM_TOLERANCE		0.013	// At which angle difference it will lock on
#LibDefine GM_LOCKEDON		0
#LibDefine GM_TURNRIGHT		1
#LibDefine GM_TURNLEFT		-1

Function Int GetFreeTid (Int Start)
{
	Int Tid = Start;
	
	While(ThingCount(T_NONE, Tid) > 0)
		Tid++;
	
	Return Tid;
}

Script 704 (Void)
{
	Int Tid = GetFreeTid(25000);
	
	If(DEBUG) Log(s:"\cdBallsAreInnert: \c[default]Assigned Tid ", d:Tid);
	
	Thing_ChangeTid(ActivatorTid(), Tid);
	
	Int PAngle = 0.0;
	Int PPitch = 0.0;
	Int Angle = 0.0;
	Int Pitch = 0.0;
	Int Speed = GetActorProperty(Tid, APROP_SPEED);
	Int Direction = GM_LOCKEDON;
	Int VelX = 0.0;
	Int VelY = 0.0;
	Int VelZ = 0.0;
	
	SetActivator(Tid, AAPTR_TARGET); // In this case, the firing actor.
	
	Angle = GetActorAngle(ActivatorTid());
	Pitch = GetActorPitch(ActivatorTid());
	
	While(GetActorProperty(Tid, APROP_HEALTH) > 0)
	{
		PAngle = GetActorAngle(ActivatorTid()); // Pointers are awesome.
		PPitch = GetActorPitch(ActivatorTid());
		
		// Do we need to turn?
		
		If(Angle - PAngle < GM_TOLERANCE && Angle - PAngle > -GM_TOLERANCE)
		{
			Direction = GM_LOCKEDON;
			Angle = PAngle;
		}
		
		// If so, calculate the turning direction...
		
		Else If((Angle - PAngle + 1.0) % 1.0 > 0.5)
			Direction = GM_TURNRIGHT;
		
		Else
			Direction = GM_TURNLEFT;
		
		// Slightly different treatment for the pitch.
		
		If(Pitch > PPitch + GM_TOLERANCE) // Too low
			Pitch -= GM_TURNSPEED;
		
		Else If(Pitch < PPitch - GM_TOLERANCE)
			Pitch += GM_TURNSPEED;
		
		Else
			Pitch = PPitch;
		
		// If we're not locked on, turn, doggammit!
		
		If(Direction != GM_LOCKEDON)
		{
			Angle = (Angle + (Direction * GM_TURNSPEED)) % 1.0;
			
			If(Angle < 0.0)
				Angle = 1.0 - Angle;
		}
		
		VelX = FixedMul(FixedMul(Cos(Angle), Speed), Cos(Pitch));
		VelY = FixedMul(FixedMul(Sin(Angle), Speed), Cos(Pitch));
		VelZ = FixedMul(-Sin(Pitch), Speed);
		
		SetActorVelocity(Tid, VelX, VelY, VelZ, FALSE, FALSE);
		SetActorAngle(Tid, Angle);
		
		If(DEBUG) Print(f:PAngle, s:"\n", f:Angle);
		
		Delay(Const:1);
	}
}
