- Home /
Unity 2D Platfomer Enemy follow player only on x-axis, c#
Hey guys, I am making a battle system for my RPG game, and I've run into a problem. I want it so if the enemy chases the player non-stop only on the x-axis. Then, when the enemy gets to a certain distance from the player, it will start attacking. Here is a script I have:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowPlayer : MonoBehaviour {
private bool checkTrigger;
public float speed;
public Transform target;
void Start () {
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform> ();
}
// Update is called once per frame
void Update () {
if (checkTrigger) {
transform.position = Vector2.MoveTowards (transform.position, target.position, speed * Time.deltaTime);
}
}
void OnTriggerEnter2D(Collider2D other) {
if (other.name == "Player") {
checkTrigger = true;
}
}
void OnTriggerExit2D(Collider2D other){
if (other.name == "Player") {
checkTrigger = false;
}
}
}
The problem is this allows the enemy to go any direction, x-axis and y-axis, but I only want the enemy to go on the x-axis only. I would really appreciate help from anyone. :)
Answer by MT369MT · Jul 04, 2018 at 07:30 PM
Hi, You could create a Vector for the destination with the two components x and y like this:
if (checkTrigger) {
transform.position = Vector2.MoveTowards (transform.position, new Vector2(target.position.x, transform.position.y), speed * Time.deltaTime);
Wow, thank you @$$anonymous$$T369$$anonymous$$T That worked! Any ideas on how to add animations for the enemy at the same time? Or is that something seperate?
What animations do you have? $$anonymous$$ove/Walk animations that you want to apply when he is moving in a specific direction or do you mean an attack animation?
I mean walking animations. I have animations of the Enemy moving left only, so I would have to use "Flip" from the SpriteRenderer at some point.
You could check if you are more right or left with the x component. For example:
if (transform.position.x > target.position.x)
{
//target is left
transform.localScale = new Vector2(-1, 1);
}
else if (transform.position.x < target.position.x)
{
//target is right
transform.localScale = new Vector2(1, 1);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612170041im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Unity 2D Platformer Enemy follow Player on X-axis only, c# 1 Answer
How to make character stop at wall? 1 Answer
Way to have 2D Sprites lit by Lights? 3 Answers
Multiple Cars not working 1 Answer