dronkowitz

FollowerNavigation.cs

Apr 26th, 2021 (edited)
646
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.25 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.AI;
  5.  
  6. public class FollowerNavigation : MonoBehaviour
  7. {
  8.     public Transform target;
  9.     public NavMeshAgent agent;
  10.     public Animator anim;
  11.     public Rigidbody body;
  12.     public bool grounded;
  13.     public LayerMask groundMask;
  14.     private bool isSetup;
  15.  
  16.     // Start is called before the first frame update
  17.     public void Setup()
  18.     {
  19.         anim = GetComponentInChildren<Animator>();
  20.         agent = GetComponent<NavMeshAgent>();
  21.         body = GetComponent<Rigidbody>();
  22.         isSetup = true;
  23.     }
  24.  
  25.     // Update is called once per frame
  26.     void Update()
  27.     {
  28.         grounded = Physics.CheckSphere(transform.position + (-transform.up * 0.55f), 0.48f, groundMask);
  29.         if (grounded)
  30.         {
  31.             agent.enabled = true;
  32.         }
  33.         if (!isSetup) return;
  34.         if (anim)
  35.         {
  36.             anim.SetFloat("Speed", agent.velocity.magnitude);
  37.         }
  38.         else
  39.         {
  40.             //Debug.LogWarning("Character is missing an animator. Please add animations to this character. " + transform.GetChild(0).name);
  41.         }
  42.         if (agent.enabled == true)
  43.         {
  44.             if(PathValid(target.position))
  45.                 agent.destination = target.position;
  46.             else
  47.             {
  48.                 agent.Warp(target.position);
  49.             }
  50.             Rotatetopos();
  51.         }
  52.        
  53.     }
  54.     public void Rotatetopos()
  55.     {
  56.         if (agent.velocity.magnitude < 0.5f)
  57.         {
  58.             transform.rotation = target.rotation;
  59.         }
  60.  
  61.     }
  62.     public void Jump(Vector3 velocity)
  63.     {
  64.         agent.enabled = false;
  65.         body.velocity = velocity;
  66.     }
  67.  
  68.     public bool PathValid(Vector3 dest)
  69.     {
  70.         float dis = Vector3.Distance(transform.position, dest);
  71.         if (dis > 10)
  72.         {
  73.             return false;
  74.         }
  75.         else return true;
  76.         /*
  77.         NavMeshPath path = new NavMeshPath();
  78.        
  79.         NavMesh.CalculatePath(transform.position, dest, NavMesh.AllAreas, path); //The Path to the wall will only work if the distance returns a valid path
  80.         return path.status == NavMeshPathStatus.PathComplete;
  81.         */
  82.     }
  83. }
  84.  
Advertisement
Add Comment
Please, Sign In to add comment