I have a Script to make an enemy chase a player… it works in single player but now that I added multiplayer I cant get it to work. How can I make the Zombie find the closest player Transform and get him to start chasing?
This is what I have now…
using UnityEngine;
using System.Collections;
public class AI : MonoBehaviour {
public Transform target;
public int Maxdistance;
public int MoveSpeed = 5;
public int RotationSpeed = 3;
private Transform mytransform;
void Awake ()
{
mytransform = transform;
}
void Start()
{
GameObject go = GameObject.FindGameObjectWithTag("Player");
target = go.transform;
Maxdistance = 2;
}
// Update is called once per frame
void Update ()
{
Debug.DrawLine(mytransform.position,target.position,Color.yellow);
mytransform.rotation = Quaternion.Slerp(mytransform.rotation,Quaternion.LookRotation(target.position - mytransform.position),RotationSpeed * Time.deltaTime);
if (Vector3.Distance(target.transform.position, mytransform.position) > Maxdistance)
{
mytransform.position += mytransform.forward * MoveSpeed * Time.deltaTime;
}
}
}
I will worry about the attacking once I get this part figured out(if your wondering)
After going over it I realized That the Start() function needed to be in the Update() function so It will continue to look for a new Transform, rather than only looking for one at the start of the game…
About to do some tests to see if it will actually switch between players
So I deleted the Start function and just added the lines to the update like this
using UnityEngine;
using System.Collections;
public class AI : MonoBehaviour {
public Transform target; // Your Player
public float Maxdistance = 2; // Distance Enemy stops from player
public int MoveSpeed = 5; // How fast The Enemy will move
public int RotationSpeed = 3; // How fast The Enemy will rotate
private Transform mytransform;
void Awake ()
{
mytransform = transform;
}
void Update ()
{
GameObject go = GameObject.FindGameObjectWithTag("Player");
target = go.transform;
Debug.DrawLine(mytransform.position,target.position,Color.yellow);
mytransform.rotation = Quaternion.Slerp(mytransform.rotation,Quaternion.LookRotation(target.position - mytransform.position),RotationSpeed * Time.deltaTime);
if (Vector3.Distance(target.transform.position, mytransform.position) > Maxdistance)
{
mytransform.position += mytransform.forward * MoveSpeed * Time.deltaTime;
}
}
}
OK after Testing, The enemy is in the game when one player spawns, but if a second player spawns the zombie disapeers… im guessing because the zombie has two players to pick from and cannoth pick so it just destroys itself?