I'm a beginner with C# and am having a bit of trouble coding an NPC that follows the player in a 2D sidescroller. The player has two speeds, a walk and a sprint. I have a very basic companion follow script but it's only set on one speed, and if I increase the speed so that the NPC will keep up when the player sprints, the NPC jitters when it follows the walking player, which makes sense. I'm just wondering if there's a way in which the NPC can dynamically follow the player in the exact same speed as the player so that this issue doesn't arise. I figure this would inquire an entirely new script, but that's fine. Again, I'm still new to all this, so any help would be greatly appreciated! Thanks!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CompanionFollow : MonoBehaviour
{
public float speed;
public float stoppingDistance;
private Transform target;
// Start is called before the first frame update
void Start()
{
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
}
// Update is called once per frame
void Update()
{
if(Vector2.Distance(transform.position, target.position) > stoppingDistance)
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
}
}