- Home /
 
               Question by 
               inanakmugan · Jul 09, 2020 at 10:54 AM · 
                spawnspawning-enemies  
              
 
              How to Spawn an enemy behind player?
Hi sorry for bad english, if you play slender the eight pages you know what i want to do. I want to spawn enemy behind of player. When player looks back jumpscare happens. I wrote something like this, this is spawns enemy when press "F" at certain distance.
 using System;
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class EnemySpawner : MonoBehaviour
 {
     //config params
     [SerializeField] GameObject EnemyPrefab;
 
     [SerializeField] Vector3 spawnDistance = new Vector3(50f,5f,0f);
 
     //params
     Vector3 PlayerPosition;
 
     enum states { first, second, third };
 
     states gameState = states.first;
 
 
     // Start is called before the first frame update
     void Start()
     {
         
     }
 
     // Update is called once per frame
     void Update()
     {
         if (Input.GetKeyDown(KeyCode.F)) 
         {
             Spawn();
         }
     }
 
     public void Spawn() 
     {
         DestroyAllOtherEnemies();
 
         Vector3 spawonpoint = getPlayerPosition().transform.position + spawnDistance;
 
         Instantiate(EnemyPrefab, spawonpoint, getPlayerPosition().transform.rotation);
 
     }
 
     private void DestroyAllOtherEnemies()
     {
         var enemies = GameObject.FindGameObjectsWithTag("Enemy");
 
         foreach(GameObject enemy in enemies) 
         {
             Destroy(enemy);
         }
 
 
     }
 
     private JumpscareController getPlayerPosition() 
     {
         return FindObjectOfType<JumpscareController>();
     }
 }
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by hacky97 · Jul 09, 2020 at 02:13 PM
It seems like you spawn the enemy at a position relative to the player position. You actually want to spawn the enemy behind the player, so line 40 should be something like:
  Vector3 spawonpoint = getPlayer().transform.TransformPoint(spawnDistance);
and the SpawnDistance should be something like:
 Vector3 spawnDistance = new Vector3(0,5,-50);
This makes an enemy spawn 50 units behind your player and 5 up.
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                