I followed a tutorial about an enemy detecting your player when you are near their radius. It worked, but I wanted my enemy to move only horizontal and vertical. What should I put or change on my code?
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public float speed = 3f;
private Transform target;
private void Update()
{
if(target != null)
{
float step = speed * Time.deltaTime;
transform.position = Vector2.MoveTowards(transform.position, target.position, step);
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.tag == "Player")
{
target = other.transform;
}
}
private void OnTriggerExit2D(Collider2D other)
{
if (other.gameObject.tag == "Player")
{
target = null;
}
}
}
`
CodePudding user response:
We need to calculate new Vector based on the direction of our target and modify that vector to not move diognally, something like following would work
private Vector2 newPosition;
private void Awake() {
newPosition = transform.position;
}
private void Update() {
if (target != null) {
float step = speed * Time.deltaTime;
float threshold = .1f;
// Only calculate new position if we are under the "threshold"
if (Vector2.Distance(transform.position, newPosition) < threshold) {
newPosition = target.position - transform.position;
if (Mathf.Abs(newPosition.x) > Mathf.Abs(newPosition.y)) {
newPosition.x = target.position.x;
newPosition.y = transform.position.y;
}
else {
newPosition.x = transform.position.x;
newPosition.y = target.position.y;
}
}
transform.position = Vector2.MoveTowards(transform.position, newPosition, step);
}
}
In here I am only calculating newPosition
if the distance between current position and newPosition
is less then some threshold
, after that I am getting new direction vector which points toward our target
, and then modifying that vector based on the biggest component of that vector.
CodePudding user response:
You could simply check which axis has the smaller delta and move in this axis first, then do the other one
private void Update()
{
if(target == null) return;
Vector2 endPosition = target.position;
Vector2 delta = target.position - transform.position;
if(Mathf.Abs(delta.x) > Mathf.Abs(delta.y))
{
// Y is the smaller delta => move only in Y
// => keep your current X
endPosition.x = transform.position.x;
}
else
{
// X is the smaller delta => move only in X
// => keep your current Y
endPosition.y = transform.position.y;
}
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}