0
\$\begingroup\$

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);
    }
}

}

\$\endgroup\$
0
\$\begingroup\$

try smoothing it out a bit with something like Vector3.SmoothDamp()

public Transform target;
float damping = .05f;
float followDistance = 2;
private Vector3 currentVelocity;


private void Update()
{
    if (target != null && Vector3.Distance(transform.position, target.position) > followDistance)
    {
        Vector3 newPos = Vector3.SmoothDamp(transform.position, target.transform.position, ref currentVelocity, damping, 10);
        transform.position = newPos;           
    }
}

you can adjust the follow distance and damping to your project.

\$\endgroup\$
  • \$\begingroup\$ That worked! Thanks so much! \$\endgroup\$ – connorwgardner Oct 26 '19 at 19:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.