Search Unity

Resolved Random movement for enemies

Discussion in 'Navigation' started by grkpektis, Apr 8, 2023.

  1. grkpektis

    grkpektis

    Joined:
    Mar 24, 2016
    Posts:
    10
    I made this code for random enemy movement but they only go left and right. Please help

    Edit- never mind I fixed it, here's the fixed script in case anyone needs it

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. public class EnemyMovement : MonoBehaviour
    4. {
    5.     public float speed = 5f; // Enemy movement speed
    6.     public float minTime = 1f; // Minimum time before changing direction
    7.     public float maxTime = 5f; // Maximum time before changing direction
    8.     private Vector3 direction; // Current movement direction
    9.     private float timer; // Timer for changing direction
    10.     private void Start()
    11.     {
    12.         // Initialize direction and timer
    13.         direction = Random.insideUnitSphere;
    14.         timer = Random.Range(minTime, maxTime);
    15.     }
    16.     private void Update()
    17.     {
    18.         // Move the enemy in the current direction
    19.         transform.Translate(direction * speed * Time.deltaTime);
    20.         // Decrement the timer
    21.         timer -= Time.deltaTime;
    22.         // If the timer reaches zero, change direction
    23.         if (timer <= 0f)
    24.         {
    25.             // Generate a new random direction
    26.             direction = Random.insideUnitSphere;
    27.             // Reset the timer
    28.             timer = Random.Range(minTime, maxTime);
    29.         }
    30.     }
    31. }
    32.  
     
    Last edited: Apr 8, 2023
    NtTNC likes this.