- Home /
How to restrict AI from following the player on the Y-axis. (2D)
Hello, I am coding my AI to follow the player when they are within a certain range of each other. As it is now, the AI does follow the player but follows on both the x and y-axis. Here is what I have for the follow code as of now:
void ChasePlayer ()
{
float distance = Vector3.Distance(transform.localPosition, target.transform.localPosition);
if (distance < 20.0f)
{
if (Vector2.Distance(transform.position, target.transform.localPosition) > 3)
{
transform.position = Vector2.MoveTowards(transform.position, new Vector2(target.transform.position.x, target.transform.position.y), speed * Time.deltaTime);
}
}
}
I'm sure I am missing something simple or am simply missing something from lack of experience, but either way I am stuck on what to do next.
Answer by MrRightclick · Jan 25, 2019 at 01:16 PM
You're changing the transform.position through Vector2.MoveTowards, to which you're giving the target as a new Vector2 with both the x and y axes. Perhaps try replacing
transform.position = Vector2.MoveTowards(transform.position, new Vector2(target.transform.position.x, target.transform.position.y), speed * Time.deltaTime);
with (if you want the AI to stay on 0 on the Y-axis)
transform.position = Vector2.MoveTowards(transform.position, new Vector2(target.transform.position.x, 0), speed * Time.deltaTime);
or replacing the target.transform.position.y with whatever number you want the AI to stay on the Y-axis.
$$anonymous$$aybe just keep the current Y value of the AI. Something like transform.position = Vector2.$$anonymous$$oveTowards(transform.position, new Vector2(target.transform.position.x, transform.position.y), speed * Time.deltaTime);
Your answer
Follow this Question
Related Questions
NPC Party Member Direction 1 Answer
Teleporting gameobject 2D 1 Answer
Prevent Y-axis Movement In 2D 0 Answers
GUI Text above Player head. 0 Answers