//-----------------------------------------------------------------------------
// Torque Game Builder
// Copyright (C) GarageGames.com, Inc.
//-----------------------------------------------------------------------------

if (!isObject(MouseShootsBehavior))
{
   %template = new BehaviorTemplate(MouseShootsBehavior);
   
   %template.friendlyName = "MouseDownFire";
   %template.behaviorType = "Input";
   %template.description  = "Continually Shoots an object while mouse down";

   %template.addBehaviorField(projectile, "The projectile to clone and shoot", object, "", t2dSceneObject);
   %template.addBehaviorField(fireRate, "The rate to fire when the fire key is held down (seconds)", float, "0.25");
   %template.addBehaviorField(projectileSpeed, "The speed of projectiles (world units per second)", float, "150");
}

// make sure we handle mouse events..
function MouseShootsBehavior::onBehaviorAdd(%this)
{
   %this.owner.setUseMouseEvents(true);
}

function MouseShootsBehavior::onBehaviorRemove(%this)
{
}

// begin firing when mouse down
function MouseShootsBehavior::onMouseDown(%this, %modifier, %worldPos)
{
	%this.fire(1);
}

// stop firing when mouse up
function MouseShootsBehavior::onMouseUp(%this, %modifier, %worldPos)
{
	%this.fire(0);
}


function MouseShootsBehavior::fire(%this, %val)
{
   if (%val == 0)
   {
      cancel(%this.fireSchedule);
      return;
   }
   
   if (!isObject(%this.projectile))
      return;
   
   %projectile = %this.projectile.cloneWithBehaviors();
   alxPlay(shoot);
   %projectile.setPosition(%this.owner.position);
   %projectile.setRotation(%this.owner.rotation);
   %projectile.setLinearVelocityPolar(%this.owner.rotation, %this.projectileSpeed);
   
// if fireRate < 0, then we want to fire once per mouse down.
   if(%this.fireRate <= 0)	
   {
      cancel(%this.fireSchedule);
      return;
   }

   if (!isEventPending(%this.fireSchedule))
      %this.fireSchedule = %this.schedule(%this.fireRate * 1000, "fire", 1);
}
