Testing player distance is not consistent
I am trying to get an enemy to follow the player when they are within a certain distance of the player. If the player gets far enough away the enemy will go back to looking for food. However my current script seems to be throwing out some weird results. Sometimes when the player is within the range it will instead decide it is not and go after the food, and about half the time when the player is outside of the range it will decide to go after the player anyway with the weird result that it will bounce back and forward undecided between player and food source.
Here is the code for determining if the player is in range, called every second.
void lookForPlayer()
{
Vector3 playerLocation = GameObject.Find("Player").transform.position;
Vector3 curentPosition = transform.position;
float playerDistance = Vector3.Distance (playerLocation, curentPosition);
if (playerDistance <= playerSearchDistance)
{
canSeePlayer = true;
print ("I can see you");
}
if (playerDistance > playerSearchDistance)
{
canSeePlayer = false;
print ("I'm hungry now.");
}
}
I have quintuple checked. The only other times the variable "canSeePlayer" appear in the code are when it is declared and the two times I check it each update to determine if it is true (face player) or false (face the food). Both of these are definitely using == to check and not =.
Is there some error in how I am arriving at the distance that would throw out this randomisation of results?
Your answer
Follow this Question
Related Questions
EXC_Bad_Access Thread CreateMaterial () 2 Answers
Getting an error: Assertion failed on expression: 'SUCCEEDED(hr)' 5 Answers
WebPlayer Build Target not showing up 1 Answer
Problem importing 3D Model 0 Answers