- Home /
Question by
brockmcn · Sep 08, 2017 at 05:36 PM ·
c#aiprogrammingfollow player
Basic AI Follow Player 2D C#
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);
}
}
Comment
Answer by smokie69 · Sep 08, 2017 at 07:24 PM
You can make the object follow the player and stop if the distance between them is less than a certain amount.
void Update() {
if (Vector3.Distance(transform.position, playerPosition) > minDistance) {
transform.position = Vector2.MoveTowards(transform.position, playerPosition,
speed * Time.deltaTime);
}
}
Also you should cache the player gameobject in the start method. Looking for it on every frame is very expensive.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
AI to follow player not working 3 Answers
Distribute terrain in zones 3 Answers
Complex Enemy follow AI 1 Answer
What are IEnumerator and Coroutine? 2 Answers