Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- [ExecuteInEditMode]
- public class CritterMovement : MonoBehaviour
- {
- public float movementDuration = 1.0f;
- public float minWaitTime;
- public float maxWaitTime;
- private bool hasArrived = false;
- public GameObject parent;
- private Coroutine moveCoroutine = null;
- private BoxCollider _parentCollider;
- public void Start()
- {
- _parentCollider = parent.GetComponent<BoxCollider>();
- }
- private void Update()
- {
- if (!hasArrived)
- {
- hasArrived = true;
- moveCoroutine = StartCoroutine(MoveToPoint(GetRandomPositionWithinBounds()));
- }
- }
- public Vector3 GetRandomPositionWithinBounds()
- {
- Bounds boundingBox = _parentCollider.bounds;
- Vector3 target = new Vector3(
- Random.Range(boundingBox.min.x, boundingBox.max.x),
- boundingBox.min.y,
- Random.Range(boundingBox.min.z, boundingBox.max.z)
- );
- return boundingBox.ClosestPoint(target);
- }
- private IEnumerator MoveToPoint(Vector3 targetPos)
- {
- float timer = 0.0f;
- Vector3 startPos = new Vector3(transform.position.x, _parentCollider.bounds.min.y, transform.position.z);
- while (timer < movementDuration)
- {
- timer += Time.deltaTime;
- float t = timer / movementDuration;
- t = t * t * t * (t * (6f * t - 15f) + 10f);
- transform.position = Vector3.Lerp(startPos, targetPos, t);
- Vector3 lookPos = targetPos - transform.position;
- lookPos.y = 0;
- Quaternion rotation = Quaternion.LookRotation(lookPos);
- float damping = 2;
- transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
- yield return null;
- }
- yield return new WaitForSeconds(Random.Range(minWaitTime,maxWaitTime));
- hasArrived = false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement