- Home /
How to have an enemy spawn a certain distance behind the player
When a door opens, I want there to be a chance that an enemy will spawn behind the player, and while I can get the enemy to spawn, they usually do so beneath the map. I vaguely know what I need but have no idea how to apply it. Basically, I need to know how to spawn something a certain distance from a moving object, like the player, based on the direction they're looking.
public class DoorSpawn : MonoBehaviour {
public GameObject self;
public GameObject player;
public GameObject enemy1;
public GameObject enemy2;
public GameObject enemy3;
Vector3 playerPos;
Vector3 playerDirection;
Vector3 spawnPos;
Quaternion playerRotation;
// Use this for initialization
void Start () {
Vector3 playerPos = player.transform.localPosition;
Vector3 playerDirection = player.transform.forward;
Quaternion playerRotation = player.transform.rotation;
Vector3 spawnPos = playerPos;
int randomValue = Random.Range (1,4);
if (randomValue == 1) {
enemy1.SetActive(true);
enemy1Spawn();
if (enemy1.activeInHierarchy == true) {
self.SetActive(false);
}
}
if (randomValue == 2) {
enemy2.SetActive(true);
enemy2Spawn();
if (enemy2.activeInHierarchy == true) {
self.SetActive(false);
}
}
if (randomValue == 3) {
enemy3.SetActive(true);
enemy3Spawn();
if (enemy3.activeInHierarchy == true) {
self.SetActive(false);
}
}
if (randomValue == 4) {
self.SetActive(false);
}
}
// Update is called once per frame
void Update () {
}
void enemy1Spawn() {
enemy1.transform.position = spawnPos;
}
void enemy2Spawn() {
enemy2.transform.position = spawnPos;
}
void enemy3Spawn() {
enemy3.transform.position = spawnPos;
}
}
Answer by shadowpuppet · Jul 24, 2017 at 08:06 PM
The doors are probably in a fixed location therefor when the player opens it he will also be in a predictable location. Why not have an empty gameobject set somewhere behind the player and the door to use as a spawnpoint? A simple LookAt script on the spawnpoint to get the enemy to face the player.It will not be a smooth lookat but the player will be looking away and not see it happen
public Transform target;//player goes here
public GameObject badGuy;
void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "enemy")
{
badGuy.transform.LookAt(target);
I thought about doing that, however it wouldn't work, the area is very large, and there are many connections between rooms and hallways, so there are a lot of doors that can be first opened from either side. I appreciate your help all the same though!