Unity 2D Platformer Enemy follow Player on X-axis only, 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. :slight_smile:

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);