Hi, I’m making a 2D, top-down, game. I’m trying to program an AI ally to help fight enemy’s.
the way it should work is, when multiple enemy’s are in range. it will chase the nearest enemy, unfortunately, the way it actually works is, if multiple enemy’s are within range, it will chase whichever enemy is first in the Hierarchy. I could really use some help.
Here’s my code, thanks in advance!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AllyMove : MonoBehaviour {
public float StartSpeed;
private float speed;
public string TargetsTag;
public string SecondaryTarget;
private Transform target;
private Transform target2;
public float chaseRange;
public float stopRange;
public float PlayerStopRange;
private bool FacingLeft = true;
void flip()
{
FacingLeft = !FacingLeft;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}
// Use this for initialization
void Start()
{
speed = StartSpeed;
target = GameObject.FindGameObjectWithTag(TargetsTag).GetComponent<Transform>();
target2 = GameObject.FindGameObjectWithTag(SecondaryTarget).GetComponent<Transform>();
}
// Update is called once per frame
void Update()
{
if (Vector2.Distance(transform.position, target.position) > stopRange && Vector2.Distance(transform.position, target.position) < chaseRange)
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
if (target.position.x > transform.position.x && FacingLeft == true)
flip();
else if (target.position.x < transform.position.x && FacingLeft == false)
flip();
}
if (Vector2.Distance(transform.position, target.position) > chaseRange && Vector2.Distance(transform.position, target2.position) > PlayerStopRange)
{
transform.position = Vector2.MoveTowards(transform.position, target2.position, speed * Time.deltaTime);
if (target2.position.x > transform.position.x && FacingLeft == true)
flip();
else if (target2.position.x < transform.position.x && FacingLeft == false)
flip();
}
}
}