- Home /
This post has been wikified, any user with enough reputation can edit it.
Question by
carter-carl30 · Jun 27, 2015 at 08:14 AM ·
spawnmovetowardsclosestnearest
Help with moving AI object to nearest spawned objects position
Hi all, I have characters in my game in hieracy named "jiji_standard" (game is 2D portrait). I have food that randomly spawns with tag "food".
What I want to do is have the nearest character to the food that spawned move to it and then collect it (i will use ontrigger enter for collecting).
I want this to keep going eg as food spawns the nearest character will go and collect it.
I found this script from another post
using UnityEngine;
using System.Collections;
public class find_nearest_food : MonoBehaviour
{
float projectileSpeed = 0;
void Update()
{
float projSpeed = projectileSpeed * Time.deltaTime;
FindClosestEnemy();
//print (FindClosestEnemy().name);
}
GameObject FindClosestEnemy()
{
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("food");
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;
}
}
I'm stuck as how to get the nearest character to move to collect the nearest food.
something like?:
jiji_standard.transform.position = Vector3.MoveTowards(transform.position, closest.position, projSpeed);
please can anybody help or advise, thankyou
Comment