When the enemies enter in the range of the tower, the arrows should hit the nearest enemy, but they are being created idle. they are not moving themselves to the target. Another thing is they are being created too fast.
This is my arrow controller. I attach this in my tower. This script receives a game object which is called arrow. It is a prefab.
// Use this for initialization
void Start()
{
InvokeRepeating( "getTarget", 0, 1.0f );
}
void Update()
{
if( target != null )
{
transform.LookAt( target );
shoot();
}
}
void shoot()
{
GameObject arrow = (GameObject)Instantiate( arrowPrefab, GameObject.Find( "spawnPoint" ).transform.position, transform.rotation );
Debug.Log( "arrow = " + arrow.transform.position );
arrow.SetActive( true );
arrow.GetComponent<Rigidbody2D>().AddForce( transform.forward * initialSpeed );
}
void getTarget()
{
GameObject[] allTaggedZombies = GameObject.FindGameObjectsWithTag( enemyTag );
float distanceDetect = Mathf.Infinity; //Initialize the var with the fartherst distance
Transform closestTargetPosition = null;
foreach( GameObject taggedTarget in allTaggedZombies )
{
distance = ( taggedTarget.transform.position - transform.position ).magnitude;
if( distance < range )
{
if( distance < distanceDetect )
{
distanceDetect = distance;
closestTargetPosition = taggedTarget.transform;
}
}
}
target = closestTargetPosition;
}