- Home /
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. :)
Answer by MT369MT · Jul 04, 2018 at 06:34 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);
what if I want to use physics ins$$anonymous$$d of only moving via transform? $$anonymous$$oveTowards() method will not work. Can't find an answer for that, can you help me?
I apreciate the help
Your answer
Follow this Question
Related Questions
Unity 2D Platfomer Enemy follow player only on x-axis, c# 1 Answer
Enemy's health wont get set from different script. 1 Answer
2D platformer- getting errors I don't understand (c#) 1 Answer
Upon shooting, Raycast target moves infinitely 1 Answer
Any way to completely learn to script in C# using Unity? 3 Answers