I am using the script below to move a transform to quickly follow a target (the player), and come to a stop close to the player.
When I move the player around, the transform is following the player, keeping the 1.5 distance.
To ensure the transform can keep up with the player, I set the moveSpeed
to 5, But when I do that, the transform jitters/stutters when moving.
If I set the moveSpeed
to 1 for example, the transform will move smoothly but will not keep up with the player - the player has to stop moving and wait for it to catch up. But increasing the speed makes the stutter return.
Why is this stutter happening, and how can I make the movement smooth?
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
public class Follow : MonoBehaviour
{
public Transform targetToFollow;
public Text text;
public Text text1;
public float lookAtRotationSpeed;
public float moveSpeed;
private float minMoveSpeed = 0f;
private Vector3 originPos;
// Start is called before the first frame update
void Start()
{
originPos = targetToFollow.position;
}
// Update is called once per frame
void Update()
{
Vector3 lTargetDir = targetToFollow.position - transform.position;
lTargetDir.y = 0.0f;
transform.rotation = Quaternion.RotateTowards(transform.rotation,
Quaternion.LookRotation(lTargetDir), Time.time * lookAtRotationSpeed);
var distance = Vector3.Distance(transform.position, targetToFollow.position);
text.text = "Transform Distance From Target " + distance.ToString();
float ms = moveSpeed;
if (distance > 5f)
{
ms = moveSpeed + 0.5f;
}
else if (distance < 1.5f)
{
ms = Mathf.Max(minMoveSpeed, ms - 0.3f);
}
else
{
//transform.position = Vector3.MoveTowards(transform.position, targetToFollow.position, Time.deltaTime * ms);
}
if (distance < 0.5f && originPos == targetToFollow.position)
{
ms = 0f;
}
if (distance > 1.5f)
transform.position = Vector3.MoveTowards(transform.position, targetToFollow.position, Time.deltaTime * ms);
originPos = targetToFollow.position;
}
}