-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathRandomMovement.cs
52 lines (42 loc) · 1.81 KB
/
RandomMovement.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI; //important
//if you use this code you are contractually obligated to like the YT video
public class RandomMovement : MonoBehaviour //don't forget to change the script name if you haven't
{
public NavMeshAgent agent;
public float range; //radius of sphere
public Transform centrePoint; //centre of the area the agent wants to move around in
//instead of centrePoint you can set it as the transform of the agent if you don't care about a specific area
void Start()
{
agent = GetComponent<NavMeshAgent>();
}
void Update()
{
if(agent.remainingDistance <= agent.stoppingDistance) //done with path
{
Vector3 point;
if (RandomPoint(centrePoint.position, range, out point)) //pass in our centre point and radius of area
{
Debug.DrawRay(point, Vector3.up, Color.blue, 1.0f); //so you can see with gizmos
agent.SetDestination(point);
}
}
}
bool RandomPoint(Vector3 center, float range, out Vector3 result)
{
Vector3 randomPoint = center + Random.insideUnitSphere * range; //random point in a sphere
NavMeshHit hit;
if (NavMesh.SamplePosition(randomPoint, out hit, 1.0f, NavMesh.AllAreas)) //documentation: https://docs.unity3d.com/ScriptReference/AI.NavMesh.SamplePosition.html
{
//the 1.0f is the max distance from the random point to a point on the navmesh, might want to increase if range is big
//or add a for loop like in the documentation
result = hit.position;
return true;
}
result = Vector3.zero;
return false;
}
}