# how to setup raycast firing system in this situation

I am working on a tower defense type game. I have a JS script that controls the movement of the tower and the rate of fire that the tower has. It instantiates little projectiles. Those projectiles have their own script attached to their prefab and are launched forward like this:

``````function Update ()
{
transform.Translate(Vector3.forward * Time.deltaTime * mySpeed);
myDist += Time.deltaTime * mySpeed;
if(myDist >= myRange)
Destroy(gameObject);
}
``````

I have the projectiles colliding with the enemy colliders and then having a message be sent to the enemy collided with. Like this:

``````function OnTriggerEnter(other : Collider)
{
if(other.gameObject.tag == "Ground Enemy")
{
Explode();
}
``````

I want to be able to increase the rate of firing speed, potentially infinitely, so I need a new way to do damage calculation. I looked into raycasting but I can’t quite grasp how to make it fit into the script. I figure that the raycasting will have to be done in the turret’s control script. The control script looks like this:

``````function Update ()
{
if(myTarget)
{
if(Time.time >= nextMoveTime)
{
CalculateAimPosition(myTarget.position);
turretBall.rotation = Quaternion.Lerp(turretBall.rotation, desiredRotation, Time.deltaTime*turnSpeed);
}

if(Time.time >= nextFireTime)
{
FireProjectile();

}
}
}

function OnTriggerEnter(other : Collider)
{
if(other.gameObject.tag == "Ground Enemy")
{
myTarget = other.gameObject.transform;
}
}
function CalculateAimPosition(targetPos : Vector3)
{
var aimPoint = Vector3(targetPos.x-transform.position.x+aimError, targetPos.y-transform.position.y+aimError, targetPos.z-transform.position.z+aimError);
desiredRotation = Quaternion.LookRotation(aimPoint);
}

function FireProjectile()
{
audio.Play();
nextMoveTime = Time.time+firePauseTime;
CalculateAimError();

for(theMuzzlePos in muzzlePositions)
{
Instantiate(myProjectile, theMuzzlePos.position, theMuzzlePos.rotation);
Instantiate(muzzleEffect, theMuzzlePos.position, theMuzzlePos.rotation);
}
}
``````

I am not sure where I should put it. To me it makes sense to put is as part of the fire projectile function and have the ray fire forward out from theMuzzlePos.position, theMuzzlePos.rotation just like the instantiated projectile and if it hits the collider with the “enemy” tag then send the “Take Damage” message. I don’t know how to do that though and I can’t find anything covering this exact use of raycast.
Can anyone help me figure out how to set this up?

If you want to get rid of the projectile altogether, then raycasting from the muzzle makes sense. You would do something like:

``````var hit : RaycastHit;
if (Physics.Raycast(theMUzzlePos.position, theMuzzlePos.forward, hit) {
if (hit.collider.tag == tagForSomethingICanDamage) {