Hello, I’m new to scripting in Unity and have been trying to script a basic enemy AI for my project. The idea is there is a trigger that the EnemyTerritory script is attached to and an enemy object the BasicEnemy is attached to. The plan is that when the player enters the trigger the territory script will tell it’s attached enemy to move towards the player, and a separate script will allow it to attack. If the player leaves the territory it will enter a rest state and do nothing. My two problems with this are that when I start the game the enemy makes a beeline for my player, even though the player is nowhere near the territory. The second is that the enemy is not restricted to only moving on the X axis, even though I have a rigidbody attached with Y and Z frozen. Any help would be greatly appreciated!
public class EnemyTerritory : MonoBehaviour
{
public BoxCollider territory;
GameObject player;
bool playerInTerritory;
public GameObject enemy;
BasicEnemy basicenemy;
// Use this for initialization
void Start ()
{
player = GameObject.FindGameObjectWithTag ("Player");
basicenemy = enemy.GetComponent <BasicEnemy> ();
playerInTerritory = false;
}
// Update is called once per frame
void Update ()
{
if (playerInTerritory = true)
{
basicenemy.MoveToPlayer ();
}
if (playerInTerritory = false)
{
basicenemy.Rest ();
}
}
void OnTriggerEnter (Collider other)
{
if (other.gameObject == player)
{
playerInTerritory = true;
}
}
void OnTriggerExit (Collider other)
{
if (other.gameObject == player)
{
playerInTerritory = false;
}
}
}
public class BasicEnemy : MonoBehaviour
{
public Transform target;
public float speed = 3f;
public float attack1Range = 1f;
public int attack1Damage = 1;
public float timeBetweenAttacks;
// Use this for initialization
void Start ()
{
Rest ();
}
// Update is called once per frame
void Update ()
{
}
public void MoveToPlayer ()
{
//rotate to look at player
transform.LookAt (target.position);
transform.Rotate (new Vector3 (0, -90, 0), Space.Self);
//move towards player
if (Vector3.Distance (transform.position, target.position) > attack1Range)
{
transform.Translate (new Vector3 (speed * Time.deltaTime, 0, 0));
}
}
public void Rest ()
{
}
}