I’m trying to make a short NPC patrol route. What I want to happen is the character moves from his starting point to the 1st point then stops moving. Instead what happens is the character just moves past the point and keeps moving in that direction forever.
After doing some debug logs, it seems the distance never actually decreases even when my character moves towards the point.
Here’s the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class WilliamsPatrol : MonoBehaviour
{
public Transform[] patrolPoints;
public int targetPoint;
public bool atDestination;
private Rigidbody2D rb;
private Animator anim;
private Vector2 moveDirection;
private Vector2 lastMoveDirection;
public float moveSpeed;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
targetPoint = 0;
atDestination = false;
}
// Update is called once per frame
void Update()
{
if (!atDestination)
{
moveDirection = (patrolPoints[targetPoint].position - transform.position).normalized;
lastMoveDirection = moveDirection;
}
if (atDestination)
{
moveDirection = Vector2.zero;
}
Animate();
}
void FixedUpdate()
{
Move();
CheckDistance();
}
void CheckDistance()
{
float xDistanceToTarget = Mathf.Abs(transform.position.x - patrolPoints[targetPoint].position.x);
float yDistanceToTarget = Mathf.Abs(transform.position.y - patrolPoints[targetPoint].position.y);
if(xDistanceToTarget <= 0.1f && yDistanceToTarget <= 0.1f)
{
atDestination = true;
}
}
void Move()
{
rb.velocity = new Vector2(moveDirection.x * moveSpeed * Time.deltaTime, moveDirection.y * moveSpeed * Time.deltaTime);
}
void Animate()
{
anim.SetFloat("AnimMoveX", moveDirection.x);
anim.SetFloat("AnimMoveY", moveDirection.y);
anim.SetFloat("AnimMoveMagnitude", moveDirection.magnitude);
anim.SetFloat("AnimLastMoveX", lastMoveDirection.x);
anim.SetFloat("AnimLastMoveY", lastMoveDirection.y);
}
}
I know I could just use a Vector2.MoveTowards
command which would be less complicated but I do it by changing the move direction because otherwise the animations don’t work.