- Home /
Check lenght from player?
Basically, I have this AI script that tracks the player, and moves to it - I was wondering if there is a way to make it only follow the player if the player is less than a length from the enemy? Thanks in advance.
This is my script:
public Transform target;
public int moveSpeed;
public int rotationSpeed;
public int maxdistance;
private Transform myTransform;
void Awake()
{
myTransform = transform;
}
void Start ()
{
maxdistance = 0;
}
void Update ()
{
if (Vector3.Distance(target.position, myTransform.position) > maxdistance)
{
// Get a direction vector from us to the target
Vector3 dir = target.position - myTransform.position;
// Normalize it so that it's a unit direction vector
dir.Normalize();
// Move ourselves in that direction
myTransform.position += dir * moveSpeed * Time.deltaTime;
}
}
}
Answer by Paulo-Henrique025 · Oct 19, 2015 at 03:46 PM
Hi, you can try this:
Transform player;
Transform _transform;
public float minDistToFollow;
public float maxDistToFollow;
void Start()
{
player = // Get your player
_transform = transform // Cache my transform to avoid GetComponent<T>
}
void FollowPlayer()
{
// Start follow Logic
}
void StopFollowPlayer()
{
// Stop follow logic
}
bool ShouldFollowPlayer()
{
if(Vector3.Distance(player.position, _transform.position) < minDistToFollow)
{
return true;
}
else
{
return false;
}
}
void Update()
{
if(ShouldFollowPlayer())
{
FollowPlayer()
}
if (Vector3.Distance(player.position, _transform.position) > maxDistToFollow)
{
StopFollowPlayer();
}
}
Answer by allenallenallen · Oct 19, 2015 at 03:47 PM
I'm actually a bit confused because your code shows that you already know the answer to your own question.
On line 24, change it to less than the "maxdistance":
if (Vector3.Distance(target.position, myTransform.position) < maxdistance)
So now the AI will only turn and follow the player when the distance between the player and the AI is less than "maxdistance"
Of course, in your void Start(), you have to change the "maxdistance" to something greater than 0.
Your answer
Follow this Question
Related Questions
2D AI, Aim at player - even when jumping? 1 Answer
[I REALLY NEED HELP FAST]Help with enemy Shooting 1 Answer
Multiple Cars not working 1 Answer
Simple AI In 2D - C# 1 Answer
A* pathfinding for 2D top Down 0 Answers