Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- public class MoveToPoint : MonoBehaviour {
- public GameObject target;
- private NavMeshAgent navAgent;
- public bool followTarget, followFromStart;
- public bool randomTarget;
- private bool isRandomTargetSet = false;
- private bool isCalculatingPath = false;
- private Vector2 randomPos;
- public float randomPointRadius;
- // Use this for initialization
- void Start() {
- navAgent = gameObject.GetComponent<NavMeshAgent>();
- if (target && followFromStart) {
- navAgent.SetDestination(target.transform.position);
- }
- }
- void Update() {
- if (target && followTarget && !randomTarget) {
- navAgent.SetDestination(target.transform.position);
- }
- if (randomTarget) {
- if (!isRandomTargetSet && !isCalculatingPath) {
- StartCoroutine(setRandomTarget());
- isCalculatingPath = true;
- }
- else {
- if (Vector3.Distance(transform.position, (Vector3)randomPos)<1) {
- isRandomTargetSet = false;
- }
- }
- }
- }
- private IEnumerator setRandomTarget() {
- Vector2 randomPos = Random.insideUnitCircle * randomPointRadius + new Vector2(transform.position.x, transform.position.z);
- navAgent.SetDestination(randomPos);
- //Wait until the path is calculated
- while (navAgent.pathPending) {
- yield return 0;
- }
- //The newPos is not contained into the NavMesh, so try again
- if (navAgent.pathStatus == NavMeshPathStatus.PathInvalid) {
- StartCoroutine(setRandomTarget());
- }
- //The new position is valid
- else {
- isRandomTargetSet = true;
- isCalculatingPath = false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement