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:
![alt text][1]
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;
}
}
}
Thanks for reading.
[1]: http://i.gyazo.com/d45183114e2ead3beef4474f5fcf5430.gif
↧