I have a script on my player that is meant to spawn an enemy 400 units away from him every 10 seconds. The enemy in turn has a script that makes it despawn if it moves 800 units away from the player. However something isn’t working properly, and I can’t figure out what’s wrong.
The issue is that when the player moves too far away from his original location, the enemies start despawning instantly. Either this means that they end up spawning too far away, meaning that they actually don’t spawn around the player, or that they miscalculate the distance to the player after a while. Or something else. I have no idea.
This is the script on the player to spawn enemies:
#pragma strict
var testEnemy : GameObject;
InvokeRepeating("SpawnDelay", 10f, 10f);
function SpawnDelay ()
{
var randomRotation = Quaternion.Euler(Random.Range(360, 10), 0, 0);
Instantiate(testEnemy, transform.position + (transform.forward * 400), randomRotation);
//testEnemy.transform.Translate(new Vector3(400f, 0, 0));
}
(The commented out line in the bottom is the other method I used for moving the enemy 400 units away from the player. Now I use “+ (transform.forward * 400)”, but neither seem to work. I’d prefer the commented out one though since the other one only spawns enemies in front of the player instead of at a random angle)
And here’s the script to make enemies despawn:
var Player : Transform;
var directionToTarget : Vector3;
var Angle : float;
var Distance : float;
var currentRotation : float;
function Update ()
{
directionToTarget = transform.position - Player.position;
Angle = Vector3.Angle(transform.forward, directionToTarget);
Distance = directionToTarget.magnitude;
if (Mathf.Abs(Angle) > 90 && Mathf.Abs(Angle) < 180 && Distance < 80)
{
//Debug.Log("I see you");
}
if (Distance > 800)
{
Destroy(gameObject);
Debug.Log("Despawned");
}
}
(There’s also a line of sight system in there, I jammed them together since they both use distance to the player)
Can someone please help me find the issue?