I’m working through part 1b of 6 and I’m wondering if this kind of manual stopping functionality is still necessary in 2019, since this project was made back in 2016.
From the PlayerController.cs script of the series Adventure Game Phase 1: The Player - Unity Learn …
public Animator animator;
public NavMeshAgent agent;
public float inputHoldDelay = .5f;
public float turnSpeedThreshold = 0.5f;
public float speedDampTime = 0.1f;
public float slowingSpeed = 0.175f;
public float turnSmoothing = 15f;
private WaitForSeconds inputHoldWait;
private Vector3 destinationPosition;
private Interactable currentInteractable;
private bool handleInput = true;
private const float stopDistanceProportion = .1f;
private const float navMeshSampleDistance = 4f;
private readonly int hashSpeedParam = Animator.StringToHash("Speed");
private readonly int hashLocomotionTag = Animator.StringToHash("Locomotion");
private void OnAnimatorMove()
{
agent.velocity = animator.deltaPosition / Time.deltaTime;
}
private void Update()
{
if(agent.pathPending)
{
return;
}
float speed = agent.desiredVelocity.magnitude;
if (agent.remainingDistance <= agent.stoppingDistance * stopDistanceProportion)
{
Stopping(out speed);
}
else if (agent.remainingDistance <= agent.stoppingDistance)
{
Slowing(out speed, agent.remainingDistance);
}
else if(speed > turnSpeedThreshold)
{
Moving();
}
animator.SetFloat(hashSpeedParam, speed, speedDampTime, Time.deltaTime);
}
private void Stopping(out float speed)
{
agent.isStopped = true;
transform.position = destinationPosition;
speed = 0f;
if (currentInteractable)
{
transform.rotation = currentInteractable.interactionLocation.rotation;
currentInteractable.Interact();
currentInteractable = null;
StartCoroutine(WaitForInteraction());
}
}
private void Slowing (out float speed, float distanceToDestination)
{
agent.isStopped = true;
transform.position = Vector3.MoveTowards(transform.position, destinationPosition, slowingSpeed * Time.deltaTime);
float proportionalDistance = 1f - distanceToDestination / agent.stoppingDistance;
Debug.Log("Proportional Distance: " + proportionalDistance + " = 1f - " + distanceToDestination + " / " + agent.stoppingDistance);
speed = Mathf.Lerp(slowingSpeed, 0, proportionalDistance);
Debug.Log("Speed: " + speed);
Quaternion targetRotation = currentInteractable ? currentInteractable.interactionLocation.rotation : transform.rotation;
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, proportionalDistance);
}
private void Moving()
{
Quaternion targetRotation = Quaternion.LookRotation(agent.desiredVelocity);
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, turnSmoothing * Time.deltaTime);
}