- Home /
Question by
cfdeisler · Apr 30, 2013 at 02:57 AM ·
gameobjectwaypointfindgameobjectswithtagvector3.distance
Can someone help me find the closest waypoint to a player?
Right now I'm trying to create a script that tells an enemy, when it spawns, the closest waypoint to the player.
var startPlayerLoc : Vector3;
var player : GameObject;
var waypoints : Array;
var otherEnemies : Array;
function Start ()
{
player = GameObject.FindGameObjectWithTag("player");
waypoints = GameObject.FindGameObjectsWithTag("waypoint");
otherEnemies = GameObject.FindGameObjectsWithTag("enemy");
startPlayerLoc = findNearest().transform.position;
}
function Update ()
{
otherEnemies = GameObject.FindGameObjectsWithTag("enemy");
startPlayerLoc = findNearest().transform.position;
}
function findNearest() : GameObject
{
waypoints = GameObject.FindGameObjectsWithTag("waypoint");
var j : int;
var smallest = Vector3.Distance(player.transform.position, waypoints[0].transform.position);
for(var i = 1; i < waypoints.length; i++)
{
if((Vector3.Distance(player.transform.position, waypoints[i].transform.position) < smallest))
{
j = i;
}
}
return waypoints[j];
}
I don't get any syntax errors but the enemy has the wrong waypoints assigned to it even when the player is standing right next to a waypoint.
Thank you for helping me
Comment
Answer by robertbu · Apr 30, 2013 at 03:00 AM
You need to update smallest as well as the index to the point:
for(var i = 1; i < waypoints.length; i++)
{
var dist = Vector3.Distance(player.transform.position, waypoints[i].transform.position);
if(dist < smallest))
{
smallest = dist;
j = i;
}
}
Your answer
Follow this Question
Related Questions
How to get if all all objects are destroyed to start another wave 1 Answer
Compare distance of many objects from current object 1 Answer
add waypoint to transform[] 2 Answers
Active GameObjects 2 Answers
RTS Resource Droppoff 2 Answers