1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
-
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.AI;
- public class NavMeshAgentController : MonoBehaviour
- {
-
-
-
- [Tooltip("Maximum distance between the starting position where the agent can be randomly placed.")]
- public float rangeAroundCurrentPosition = 5.0f;
-
-
-
-
-
-
-
- bool RandomPoint(Vector3 center, float range, out Vector3 result)
- {
-
- for (int i = 0; i < 30; i++)
- {
- Vector3 vector = Random.insideUnitSphere * range;
- if (Vector3.Dot(vector, -Vector3.up) < 0)
- {
- vector = -vector;
- }
- RaycastHit rayHit;
- if (!Physics.Raycast(center + transform.up, vector, out rayHit))
- {
- continue;
- }
- Vector3 randomPoint = rayHit.point;
- NavMeshHit hit;
- if (NavMesh.SamplePosition(randomPoint, out hit, 1.0f, NavMesh.AllAreas))
- {
- result = hit.position;
- return true;
- }
- }
- result = Vector3.zero;
- return false;
- }
-
-
-
-
- public bool Move()
- {
- Vector3 point;
- if (RandomPoint(transform.position, rangeAroundCurrentPosition, out point))
- {
- transform.position = point;
- return true;
- }
- return false;
- }
- }
|