# Missile Behavior improvement

I have a missile that follow the nearest target with a specific tag. ok so now… its perfect.
But i want that: when a missile pass the target (relative to player) the missile do not follow anymore… just translate forward.

something like this pseudocode:

distance of missile relative to player;
distance of target relative to player;

when the distance of missile > distance of target
just go forward;

and this is my actual code:

``````using UnityEngine;
using System.Collections;

public class Missle : MonoBehaviour {

public string searchTag;
private GameObject closetMissle;
private Transform target;
public GameObject missileExpObject;

void Start()
{
closetMissle = FindClosestEnemy();

if(closetMissle)
target = closetMissle.transform;
}

void Update()
{

transform.LookAt(target);
transform.Translate(Vector3.forward * 30f * Time.deltaTime);

if(target == null)
{
closetMissle = FindClosestEnemy();

if(closetMissle)
{
target = closetMissle.transform;
}
}
Destroy (this.gameObject,12);
}

GameObject FindClosestEnemy()
{
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag(searchTag);

GameObject closest = null;
float distance = Mathf.Infinity;

Vector3 position = transform.position;

foreach(GameObject go in gos)
{
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;

if(curDistance < distance)
{
closest = go;
distance = curDistance;
}
}

return closest;
}
}
``````

where i put this implementation? and how
regards…

You can use a sphere cast that casts forward once every second/x amount of frames and when it doesn’t have a hit of the player anymore, stop casting and stop looking at target. Which means transform.LookAt() will need too be in an if(bool) statement, and the spherecast will if it gets a hit will set bool to true, and if not it will set bool to false. That’s the best way I could think of. Sphere casting might use a lot of math though. So you might want to check by angle between the target and the missile forward.