- Home /
Move missile to nearest target
Hey guys so I need some help here.
I have a working homing missile script that chooses a random city to go to and destroy. However randomly choosing a target is very difficult to keep in a game like this. Basically I am making a missile command game for my class.
Don't worry my instructor said we can use the forums for help if need be.
What I want the game to do is chosen the nearest city to destroy. Then if there aren't any cities left they need to stop or despawn(this shouldn't be hard to figure out for me)
Is there any methods to choosing the nearest target city? My cites are in a array here is my script:
public GameObject[] targets;
public float speed;
private Rigidbody rb;
private GameObject chosenTarget;
void Start()
{
rb = GetComponent<Rigidbody>();
ChooseTarget();
}
void ChooseTarget()
{
chosenTarget = targets[Random.Range(0, targets.Length)];
}
void FixedUpdate()
{
transform.LookAt(chosenTarget.transform.position);
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, chosenTarget.transform.position, step);
}
Right now it chooses the cities at random but I am stumped on how to make them choose the nearest target. Thanks for any help.
Answer by ExtinctSpecie · Apr 16, 2017 at 10:55 PM
float shortestDistance = Mathf.Infinity;
foreach (GameObject enemy in enemies)
{
float distanceToEnemy = Vector3.Distance(transform.position, enemy.transform.position);
if (distanceToEnemy < shortestDistance)
{
shortestDistance = distanceToEnemy;
nearestEnemy = enemy;
}
}
hope this helps
Thanks where would I put this function? in my ChooseTarget function?
yes and anytime you want to get the closest target call that method
hey question just started working with it. What do you mean by "nearestEnemy" cause that was never called anywhere.
Your answer
Follow this Question
Related Questions
Missiles move to already destroy objects [Problem][Update] 4 Answers
Homing Missiles that target where you were 0 Answers
Homing Missile Target From Parent - Help 1 Answer
Homing missile: choosing a new target 1 Answer
Homing missle with raycast 1 Answer