- Home /
Does anybody know how to make it to where the enemy just stops short?
I have been trying for hours and I can't seem to get it to work, in my script the enemy is supposed to follow you when you get close and go back to a set point when you get too far but I need the enemy to stop when it gets within a certain range of you, I just can't seem to do it; If any of you could help me that I would appreciate it! Here is my code:
public float speed = 5f;
private Transform target;
public Transform returnPoint;
void Start()
{
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
}
public void Update()
{
if(Vector2.Distance(transform.position, target.position) <= 5f)
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
else if (Vector2.Distance(transform.position, target.position) >= 10f)
{
transform.position = Vector2.MoveTowards(transform.position, returnPoint.position, speed * Time.deltaTime);
}
}
Answer by FeedMyKids1 · Jan 11, 2021 at 03:22 PM
public float speed = 5f;
private Transform target;
public Transform returnPoint;
[SerializeField] float stopShortDistance = 1.0f;
void Start()
{
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
}
public void Update()
{
float distanceToTarget = Vector2.Distance(transform.position, target.position);
if(distanceToTarget <= 5f && distanceToTarget > stopShortDistance)
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
else if (distanceToTarget >= 10f)
{
transform.position = Vector2.MoveTowards(transform.position, returnPoint.position, speed * Time.deltaTime);
}
}
Cache the distance calculation since it´s the same for both 'if' blocks.
If the Target is within distance of your object (distance stopShortDistance), it will move toward the target.
Otherwise, if it's more than ten meters away from the target, it will move back to the start position.
Thank you so much, it worked! At first I tried it and it had the same problem but I just raised the stop short distance and it worked great!
Answer by logicandchaos · Jan 11, 2021 at 03:25 PM
You need to create another else if block where you have the condition where you want the enemy to stop and you can just have it empty since you are not using physics to move.
Your answer
![](https://koobas.hobune.stream/wayback/20220613023106im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Brackeys EnemyAi Script 0 Answers
How to fix this Score UI problem 2 Answers
How to make player hides from an enemy ? 0 Answers
2D Field of View 2 Answers