- Home /
Problems with AI script
I'm making a game where the player is being chased by numerous enemy cars who are operated by AI. I have this script below to handle to AI. It works fine with just one enemy in the scene but when I spawn multiple, they all combine into one car and get very glitchy. How can I fix this? Thanks.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AI : MonoBehaviour {
public Transform Player;
int MoveSpeed = 15;
int MaxDist = 10;
int MinDist = 5;
void Update()
{
transform.LookAt(Player);
if (Vector3.Distance(transform.position, Player.position) >= MinDist)
{
transform.position += transform.forward * MoveSpeed * Time.deltaTime;
if (Vector3.Distance(transform.position, Player.position) <= MaxDist)
{
//Saved for later when I add attacking
}
}
}
}
Answer by rhapen · Oct 24, 2020 at 11:18 PM
you are moving them by exactly same vector. so you have to add offset separately to each instantiated car. example. You might want to calculate and recalculate the offset somehow based on your scene.
Vector3 offset = new Vector3(0, 2, 0);
void Start()
{
transform.position = transform.position+offset;
}
Answer by jamesorion44 · Oct 25, 2020 at 01:51 PM
@rhapen This is my script with your part attached. I want to make sure that I did it correctly because there has been no change in the AI's behavior.
public Transform Player;
int MoveSpeed = 15;
int MaxDist = 10;
int MinDist = 5;
Vector3 offset = new Vector3(7, 0, 7);
void Start()
{
transform.position = transform.position + offset;
}
void Update()
{
transform.LookAt(Player);
if (Vector3.Distance(transform.position, Player.position) <= MaxDist)
{
//Saved for later when I add attacking
}
}
}