- Home /
How do I make the enemy lock onto the player's x-axis coordinates?
Currently I have the enemy fully locked on the player, but I'm trying to make the enemy character move towards the player's x-axis coordinates while forever moving down the y-axis.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Enemy : MonoBehaviour {
public float moveSpeed;
public Transform target;
void Start()
{
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
}
// Update is called once per frame
void Update()
{
if(Vector2.Distance(transform.position, target.position) > 0.5)
{
transform.position = Vector2.MoveTowards(transform.position, target.position, moveSpeed * Time.deltaTime);
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Destroy"))
{
Destroy(gameObject);
}
}
}
Comment
Best Answer
Answer by Ymrasu · Aug 11, 2020 at 09:34 AM
One way is that you could separate the two axis movements and pretend the player is always on the same y-axis, like so:
if (Vector2.Distance(transform.position, target.position) > 0.5f) {
// Chase on x-axis
Vector2 xTarget = new Vector2(target.position.x, transform.position.y);
transform.position = Vector2.MoveTowards(transform.position, xTarget, moveSpeed * Time.deltaTime);
// Move down on y-axis
transform.position += Vector3.down * moveSpeed * Time.deltaTime;
}
Although the movement speed would not be normalized (it would move faster diagonally). But that is an easy fix.