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…