Is there a better option than Vector2.MoveTowards for the movement of my NPC

I know that directly setting the position isn’t recommended and that usual way to move the npc would be using .AddForce() in the rigid body. But this NPC is constantly following the player arround, and only moves in straight lines, and I coundn’t get a satisfying result out of adding forces to the RigidBody. I settled on using Vector2.MoveTowards(), here is a simplified example of the code:

private Vector2 FollowPlayer()
{
     if(playerDistance < followDistance)
     {
          return currentPosition;
     } 
     else 
     {
          return Vector2.MoveTowards(currentPosition, currentPosition + adjustedMovement, speed * Time.deltaTime);
     }
}

Then on the Move() method of this NPC I constantly set his position to the value returned by FollowPlayer():

private void Move()
{
     Vector2 targetPosition = FollowPlayer();
     transform.position = targetPosition;
}

This is working, but the movement isn’t very smoth, is there a better way of doing this than using Vector2.MoveTowards() that would lead to smoother movement? Slowing his speed down works, but then he can’t keep up with the player. I would preffer to still directly set his position since it’s easier to control exaclty how he moves, but I’m open to any tips or advice.

rb.MovePosition(rb.position + (targetPosition - rb.position) * speed * Time.deltaTime);

try unity ai navigation.

1 Like

You can use Transform.Translate to combine the functionality into one line. This won’t make it smoother though.

I’m guessing the lack of smoothness may be that you’re applying the Move from within FixedUpdate which runs at 50 Hz while Update runs at 60 Hz and even up to 240 Hz or more (vsync off). So make sure you call Move() from Update() not FixedUpdate().

Also if the object still has a Rigidbody consider removing it. If you do need it at some time, disable it. And make sure when it’s enabled and you don’t move the object via forces then you have to set IsKinematic to true, otherwise the object will still be influenced by other physics forces.