hi there i have a script which works pretty much how want to to except it would be nice if i could get the ai to ether move to the rear of the player at all points of go in the direction the player is facing
here is the code so far
any help would be great by the way its a 2d game
using UnityEngine;
public class PlaerAI : MonoBehaviour
{
public Transform playerPos;
public GameObject Player;
public float speed;
public float mobRange;
Animator animator;
bool isMoving;
void Start()
{
Player = GameObject.FindGameObjectWithTag("Player");
animator = GetComponent<Animator>();
}
private void Update()
{
TotDistance();
}
void TotDistance()
{
var testX = transform.position.x;
var testY = transform.position.y;
var pTestX = Player.transform.position.x;
var pTestY = Player.transform.position.y;
var xDistance = testX - pTestX;
var yDistance = testY - pTestY;
var totDistance = Mathf.Pow(xDistance, 2) + Mathf.Pow(yDistance, 2);
totDistance = Mathf.Sqrt(totDistance);
Debug.Log("Total Distance: " + totDistance);
FacePlayer(xDistance, totDistance);
}
void FacePlayer(float xDistunce, float tutDistunce)
{
if (xDistunce < -0.5)
{
transform.localScale = new Vector3(2, 2, 1);
if (tutDistunce > mobRange)
{
transform.Translate(speed * Time.deltaTime, 0, 0, Space.World);
animator.SetBool("isMoving", isMoving = true);
}
else
{
animator.SetBool("isMoving", isMoving = false);
}
}
if (xDistunce > 0.5)
{
transform.localScale = new Vector3(-2, 2, 1);
if (tutDistunce > mobRange)
{
transform.Translate(-speed * Time.deltaTime, 0, 0, Space.World);
animator.SetBool("isMoving", isMoving = true);
}
else
{
animator.SetBool("isMoving", isMoving = false);
}
}
}
}
You could check player’s forward direction (the direction that is your forward movement direction) and then use this to set a point behind the player at the desired distance, like 2 units behind the player and move your enemies toward that point?
You can find examples how to do this if you do some googling.
I’m working on a work around as the ai has a rigidbody2d which is need for parts of the game and also trying to get it to jump over things as when needed