Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.AI;
- namespace DunGen.NavigationDemo
- {
- public sealed class ClickToMove : MonoBehaviour
- {
- public Camera Camera;
- public NavMeshAgent Agent;
- public Animator Animator;
- private bool isTraversingLink;
- private float traversalSpeed;
- private Vector3 previousPosition;
- private void Update()
- {
- if (Agent.isOnOffMeshLink)
- {
- if (!isTraversingLink)
- {
- // The agent seems to snap to the entry point on the link
- // We reset the agent to its last position to smooth out the transition
- Agent.transform.position = previousPosition;
- // Use our current speed for the duration of the link
- traversalSpeed = CalculateCurrentVelocity().magnitude;
- // Just to be safe, ensure we're using a valid speed
- if (traversalSpeed <= 0.0f)
- traversalSpeed = Agent.speed;
- isTraversingLink = true;
- }
- TraverseOffMeshLink();
- }
- UpdateAnimator();
- previousPosition = Agent.transform.position;
- }
- private Vector3 CalculateCurrentVelocity()
- {
- return (Agent.transform.position - previousPosition) / Time.deltaTime;
- }
- private void TraverseOffMeshLink()
- {
- var link = Agent.currentOffMeshLinkData;
- Vector3 destination = link.endPos + Vector3.up * Agent.baseOffset;
- Vector3 toDestination = destination - Agent.transform.position;
- float distanceToDestination = toDestination.magnitude;
- // If we're close enough, consider the traversal complete
- if (distanceToDestination <= 0.01f)
- {
- Agent.updateRotation = true;
- Agent.CompleteOffMeshLink();
- isTraversingLink = false;
- }
- else
- {
- Vector3 targetForwardDirection = toDestination.normalized;
- Quaternion targetRotation = Quaternion.LookRotation(targetForwardDirection, Vector3.up);
- float maxPositionDelta = Agent.speed * Time.deltaTime;
- float maxRotationDelta = Agent.angularSpeed * Time.deltaTime;
- Agent.updateRotation = false; // We'll update the agent's rotation manually while traversing the link
- Agent.transform.position = Vector3.MoveTowards(Agent.transform.position, destination, maxPositionDelta);
- Agent.transform.rotation = Quaternion.RotateTowards(Agent.transform.rotation, targetRotation, maxRotationDelta);
- }
- }
- private void UpdateAnimator()
- {
- // Update animator
- if (Animator == null)
- return;
- Vector3 currentPosition = Agent.transform.position;
- Vector3 velocity = CalculateCurrentVelocity();
- float speed = velocity.magnitude;
- Animator.SetFloat("velx", velocity.x);
- Animator.SetFloat("vely", velocity.z);
- Animator.SetBool("move", speed > 0f);
- Animator.SetFloat("Speed", speed);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement