Hi, I am currently learning programming and making a 2D rpg game. I’ve encountered a problem which I haven’t been able to fix for 2 whole days… It’s really getting to my nerves now and I can’t find any solution. The problem is that the enemy detects the player/target, only if it was spawned near the player. If I spawn it far away and go near it, it doesn’t detect my player. And when it has detected, it only moves to the position it detected the player and gets stuck there
Here’s a gif:
As you can see, the enemies are moving where I was. It’s like the script is only checking the code once.
Here’s the code:
public class EnemyAI : MonoBehaviour {
[SerializeField]
private float maxSqrDistance = 16, //4 meters
moveSpeed = 1f;
public Transform target;
void Update () {
//Vector between the 2 entities
Vector3 dir = target.position - transform.position;
float distance = dir.sqrMagnitude, //Length squared because a sqrt is expensive
dot = Vector3.Dot(transform.forward, dir.normalized);
if (distance < maxSqrDistance) //Is the distance less than what we want?
{
Debug.Log("Within range!");
//Move in the direction, so towards the player
transform.position += dir.normalized * moveSpeed * Time.deltaTime;
}
}
}
First off that private variable doesn’t need to be serialized. My advice would be to switch the target variable type to GameObject. My guess is it’s not updating the reference to your player since a transform was passed in as a public variable. Try this and see what happens:
public class EnemyAI : MonoBehaviour
{
private float maxSqrDistance = 16 //4 meters
public float moveSpeed = 1f; //So you can tweak move speed in the editor or in enemy prefabs
public GameObject target;
void Update () {
//Vector between the 2 entities
Vector3 dir = target.transform.position - transform.position;
float distance = dir.sqrMagnitude, //Length squared because a sqrt is expensive
dot = Vector3.Dot(transform.forward, dir.normalized);
if (distance < maxSqrDistance) //Is the distance less than what we want?
{
Debug.Log("Within range!");
//Move in the direction, so towards the player
transform.position += dir.normalized * moveSpeed * Time.deltaTime;
}
}
}
Finally, why not use Vector2 instead of Vector3? It looks like a 2D game, so you dont need to keep track of a 3’rd axis.