Advertisement
Krythic

CritterMovement

May 1st, 2023
918
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.98 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. [ExecuteInEditMode]
  5. public class CritterMovement : MonoBehaviour
  6. {
  7.  
  8.     public float movementDuration = 1.0f;
  9.     public float minWaitTime;
  10.     public float maxWaitTime;
  11.     private bool hasArrived = false;
  12.     public GameObject parent;
  13.     private Coroutine moveCoroutine = null;
  14.     private BoxCollider _parentCollider;
  15.  
  16.     public void Start()
  17.     {
  18.         _parentCollider = parent.GetComponent<BoxCollider>();
  19.     }
  20.  
  21.     private void Update()
  22.     {
  23.         if (!hasArrived)
  24.         {
  25.             hasArrived = true;
  26.             moveCoroutine = StartCoroutine(MoveToPoint(GetRandomPositionWithinBounds()));
  27.         }
  28.     }
  29.  
  30.     public Vector3 GetRandomPositionWithinBounds()
  31.     {
  32.         Bounds boundingBox = _parentCollider.bounds;
  33.         Vector3 target = new Vector3(
  34.             Random.Range(boundingBox.min.x, boundingBox.max.x),
  35.             boundingBox.min.y,
  36.             Random.Range(boundingBox.min.z, boundingBox.max.z)
  37.         );
  38.         return boundingBox.ClosestPoint(target);
  39.     }
  40.  
  41.     private IEnumerator MoveToPoint(Vector3 targetPos)
  42.     {
  43.         float timer = 0.0f;
  44.         Vector3 startPos = new Vector3(transform.position.x, _parentCollider.bounds.min.y, transform.position.z);
  45.  
  46.         while (timer < movementDuration)
  47.         {
  48.             timer += Time.deltaTime;
  49.             float t = timer / movementDuration;
  50.             t = t * t * t * (t * (6f * t - 15f) + 10f);
  51.             transform.position = Vector3.Lerp(startPos, targetPos, t);
  52.             Vector3 lookPos = targetPos - transform.position;
  53.             lookPos.y = 0;
  54.             Quaternion rotation = Quaternion.LookRotation(lookPos);
  55.             float damping = 2;
  56.             transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
  57.             yield return null;
  58.         }
  59.  
  60.         yield return new WaitForSeconds(Random.Range(minWaitTime,maxWaitTime));
  61.         hasArrived = false;
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement