- Home /
Problems with pathfinding algorithm
#pragma strict
@HideInInspector var enemies : GameObject[];
var player : GameObject;
var speed : float = 6;
static var first : boolean = false;
function Start ()
{
player = GameObject.FindGameObjectWithTag("Player");
if (!player)
Debug.Log ("ERROR could not find Player!");
}
function Update()
{
var moveSpeed = speed * Time.deltaTime;
enemies=GameObject.FindGameObjectsWithTag(gameObject.tag);
if (!player)
return;
var distance = Vector3.Distance( player.transform.position, transform.position);
if (first == true)
{
enemies[0] = gameObject;
if ( distance < 100)
{
Debug.Log ("player is close");
transform.LookAt(player.transform);
var delta = player.transform.position - transform.position;
delta.Normalize();
transform.position = transform.position + (delta * moveSpeed);
}
else
{
Debug.Log("searching for enemy");
var delta2 = Random.insideUnitSphere;
delta2.Normalize();
transform.position = transform.position + (delta2 * moveSpeed);
}
}
else
{
gameObject.transform.position = Vector3.MoveTowards(gameObject.transform.position,enemies[0].transform.position, moveSpeed);
}
}
the problem here is in the last part else { gameObject.transform.position = Vector3.MoveTowards(gameObject.transform.position,enemies[0].transform.position, moveSpeed); }
When the first enemy is on its own it follows the instructions well, but when there are more than one it disregards the rest of the code and just chooses a random direction and just translates itself in that direction until the end of the map even if the player is closeby - the other gameObjects follow it as they should. the boolean variable is changed to true or false in another script file, but there's no problem with that so I don't feel the need to include that.
Your answer
Follow this Question
Related Questions
how to reference GameObjects to GUIButton??? 1 Answer
Return to Start Position 1 Answer
How to make this kind of control ? 2 Answers
Accessing game object based on position 2 Answers