Basically I want the AI to follow the player from behind at all times. I plan on using transform.rotation but I ran into some problems so I am just using an int for now. Below is what I have so far…
public Transform playerPos;
public float speed;
Vector2 pos;
Vector2 targetPos;
int rot;
void Start () {
pos = transform.position;
}
void Update () {
rot = GameObject.Find("Player").GetComponent<PlayerController>().rot; //Player rotation
//Make AI always move to back of player
if (rot == 0)
targetPos = new Vector2(playerPos.position.x - 1, playerPos.position.y);
else if (rot == 90)
targetPos = new Vector2(playerPos.position.x, playerPos.position.y - 1);
else if (rot == 180)
targetPos = new Vector2(playerPos.position.x + 1, playerPos.position.y);
else if (rot == 270)
targetPos = new Vector2(playerPos.position.x, playerPos.position.y + 1);
//Move AI to target position
if (new Vector3(pos.x, pos.y, 0) == transform.position)
{
if (pos.x != targetPos.x)
{
if (pos.x > targetPos.x)
pos.x -= 1;
else
pos.x += 1;
}
else if (pos.y != targetPos.y)
{
if (pos.y > targetPos.y)
pos.y -= 1;
else
pos.y += 1;
}
}
transform.position = Vector2.MoveTowards(transform.position, pos, speed * Time.deltaTime);
}
}