- Home /
AI script that follows player in a distance
I wrote a script that makes allies to follow the leader. Now I'm struggling to make the allies follow the leader not from all over the map but within a range. if someone can help me out or give me a hint it would be much appreciated! here's the code:
public class AlliesFollowing : MonoBehaviour
{
public float speed;
private Transform target;
void Start()
{
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
}
void Update()
{
if (Vector2.Distance(transform.position, target.position) > 1 )
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
}
}
Answer by wooolly · Aug 21, 2020 at 08:40 PM
You're already using a Vector Distance check to ensure they stop following when within 1 tile, so why not just do the same thing with a max distance? I used 30 tiles just as an example.
float distance = Vector2.Distance(transform.position, target.position);
if (distance > 1f && distance < 30f)
{
// Follow
}
Preferably replace these hard-coded values (1, 30) with CONSTANT fields so that you can add a descriptive name and re-use them when necessary.
Your answer
Follow this Question
Related Questions
Top Down Camera? 0 Answers
overhead game in 2d world? 0 Answers
Why does a rigidbody won't move on my EnemyMovement class? 0 Answers
Cannot change the value of this integer that I use for array,Cannot change the value of this one. 0 Answers
How generate a 2D picture puzzle from a sprite visible on game scene 1 Answer