I’m trying to make a follow catch up script logic.
When the transform distance is more then 5 from the target make the transform speed increasing to catch up the target when getting close to the target slow down and keep following the target.
If when running the game or in some cases the distance is more then 5 and the target is not moving increase the speed and slow down to stop near the target. but if the target is in a move then increase the speed until getting close to the target then slow down and keep follow the target.
When following the target increase/decrease the speed according to the target speed movement.
Now when running the game both conditions are true so it’s increasing the speed also when the transform already catch up the target even if the target is not moving at all so the transform hit the target in high speed instead slow down stop near the target.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Follow : MonoBehaviour
{
public Transform targetToFollow;
public Text text;
public float lookAtRotationSpeed;
public float moveSpeed;
private float minMoveSpeed = 0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void FixedUpdate()
{
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 = distance.ToString();
if(distance > 5f)
{
moveSpeed += 0.5f * Time.deltaTime;
}
if (distance > 1.5f && distance < 5f)
{
moveSpeed += 0.7f;
}
else if (distance < 1f)
{
moveSpeed = Mathf.Max(minMoveSpeed, moveSpeed - 0.3f);
}
transform.position = Vector3.MoveTowards(transform.position, targetToFollow.position, Time.deltaTime * moveSpeed);
}
}
There might be later more or other rules that can be add but for now I want to make some kind of catch up follow logic script. Something like when in game there is a dog that follow the player and walk “beside” the player.