Search Unity

how to make my enemies move towards me one after the other after being spawned

Discussion in 'Scripting' started by airesdav, Mar 29, 2013.

  1. airesdav

    airesdav

    Joined:
    Nov 13, 2012
    Posts:
    128
    Hi guys,

    I have a spawn system in place where it spawns and enemy one after the other which is fine, but after they spawn I want them to move towards me, I know that I have to use the lookat function and get it to move towards my player , but I m struggling where I would put it in my code, I don't whether I put in a start function or Update here is my code below, please see code below that I have for my enemies spawning: :)
    Code (csharp):
    1.  
    2.  
    3.  
    4. using UnityEngine;
    5. using System.Collections;
    6.  
    7. public class zombiespawn : MonoBehaviour
    8. {
    9.   // Spawn location
    10.   public Vector3 spawnLocation = Vector3.zero;
    11.   // Spawn radius (Gives a bit more randomness factor to the spawn location)
    12.   public float spawnRadius = 1.0f;
    13.   // Spawn timer (seconds)
    14.   public float spawnTimer = 2.0f;
    15.   private float spawnTimeRemaining = 5.0f;
    16.    
    17.     // *** test code ***
    18.    
    19.    
    20.    
    21.     // The zombie to spawn
    22.     public GameObject zombiePrefab = null;
    23.  
    24. void Awake()
    25.     {
    26.     spawnTimeRemaining = spawnTimer;
    27.     }
    28.    
    29.  
    30.    
    31.  
    32.     void FixedUpdate()
    33.     {
    34.     spawnTimeRemaining -= Time.deltaTime;
    35.  
    36.     if (spawnTimeRemaining < 0.0f)
    37.     {
    38.       Vector2 circlePosition = Random.insideUnitCircle * spawnRadius;
    39.       GameObject.Instantiate(zombiePrefab, spawnLocation + new Vector3(circlePosition.x, 0.0f, circlePosition.y), Quaternion.identity);
    40.  
    41.       spawnTimeRemaining = spawnTimer;
    42.     }
    43.   }
    44. }
    45.    
    46.  
    47.  
    48.  
    49.  
     
  2. stridervan

    stridervan

    Joined:
    Nov 11, 2011
    Posts:
    141
    Inside your enemy code you'd do something like

    Code (csharp):
    1.  
    2. void OnUpdate()
    3. {
    4.   var dirVector = player.transform.positon - this.transform.position; // calculating the direction vector
    5.   var dirVector = dirVector.normalized; // normalizing the vector
    6.   this.transform.position = this.transform.position + dirVector * speed * Time.deltaTime; // moving the enemy with a speed
    7. }
    8.  
     
  3. airesdav

    airesdav

    Joined:
    Nov 13, 2012
    Posts:
    128
    Thanks for the help stridervan I appreciate it will give it a go :)