Reputation: 51
I Have started a new game.I have an enemy, and when the player is on a certain distance from the enemy, he attacks.My script works and the enemy follows the player, but despite the number I set there it's following the player. I need the enemy follow only after being close enough to the player. I have an empty object attached to the enemy and the script is on it.
I looked for the answer in unity community answers and find the script i use in this link https://answers.unity.com/questions/274809/how-to-make-enemy-chase-player-basic-ai.html and also i have googled it but couldn't find any correct solution for it .
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AIController : MonoBehaviour
{
public int AttackTrigger2;
public Transform Player;
public int MoveSpeed = 4;
public int MaxDist = 10;
public int MinDist = 5;
void Update()
{
transform.LookAt(Player);
if (Vector3.Distance(transform.position, Player.position) >= MinDist)
{
transform.position += transform.forward * MoveSpeed * Time.deltaTime;
if (Vector3.Distance(transform.position, Player.position) <= MaxDist)
{
//Here Call any function U want Like Shoot at here or something
}
}
}
}
I have no errors on my code, he does what i need but i need enemy stop following the player after my player is from a certain distance.
Upvotes: 2
Views: 4522
Reputation: 178
You should change condition in first if
case.
According to your code enemy will follow the player, if distance between them is grater than MinDist.
Replace >=
with<=
.
And I think you may have wanted something like this.
if (Vector3.Distance(transform.position, Player.position) <= MaxDist)//not MinDist
{
transform.position += transform.forward * MoveSpeed * Time.deltaTime;
if (Vector3.Distance(transform.position, Player.position) <= MinDist)//not MaxDist
{
//Here Call any function you want, like Shoot or something
}
}
Upvotes: 1
Reputation: 682
I'm guessing that the next answer in the forum you linked actually solves your problem. The problem is simply copying and pasting without understanding why something behaves like it should. In this case:
>= MinDist
Means that the enemy will follow the player as long as it's greater than or equal to MinDist
, in this case 5. I'm guessing that you want is:
<= MaxDist
so that the enemy only follows if it's less than 10 away. If it's over 10 away, stop following.
Upvotes: 2