NodeCanvas Forums › Support › Non-Random Patrol › Reply To: Non-Random Patrol
Hello,
Here is a modified version of Patrol.cs script. This will also be included in the next version.
There is now an option to set the patrol either Random or Progressive.
Please open Patrol.cs and replace all the code with the following:
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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
using System.Collections.Generic; using NodeCanvas.Framework; using ParadoxNotion.Design; using UnityEngine; namespace NodeCanvas.Tasks.Actions{ [Category("Movement")] [Description("Move randomly between various game object positions taken from the list provided")] public class Patrol : ActionTask<NavMeshAgent> { public enum PatrolMode{ Progressive, Random } [RequiredField] public BBParameter<List<GameObject>> targetList; public BBParameter<PatrolMode> patrolMode = PatrolMode.Random; public BBParameter<float> speed = 3; public float keepDistance = 0.1f; private int index = -1; private Vector3? lastRequest; protected override string info{ get {return string.Format("{0} Patrol {1}", patrolMode, targetList);} } protected override void OnExecute(){ if (patrolMode.value == PatrolMode.Random){ var newIndex = Random.Range(0, targetList.value.Count); while(newIndex == index){ newIndex = Random.Range(0, targetList.value.Count); } index = newIndex; } else if (patrolMode.value == PatrolMode.Progressive) { index = (int)Mathf.Repeat(index + 1, targetList.value.Count); } var targetGo = targetList.value[index]; if (targetGo == null){ Debug.LogWarning("List's game object is null on MoveToFromList Action"); EndAction(false); return; } var targetPos = targetGo.transform.position; agent.speed = speed.value; if ( (agent.transform.position - targetPos).magnitude < agent.stoppingDistance + keepDistance){ EndAction(true); return; } Go(); } protected override void OnUpdate(){ Go(); } void Go(){ var targetPos = targetList.value[index].transform.position; if (lastRequest != targetPos){ if ( !agent.SetDestination( targetPos) ){ EndAction(false); return; } } lastRequest = targetPos; if (!agent.pathPending && agent.remainingDistance <= agent.stoppingDistance + keepDistance){ EndAction(true); } } protected override void OnStop(){ lastRequest = null; if (agent.gameObject.activeSelf){ agent.ResetPath(); } } protected override void OnPause(){ OnStop(); } public override void OnDrawGizmosSelected(){ if (agent && targetList.value != null){ foreach (var go in targetList.value){ if (go) Gizmos.DrawSphere(go.transform.position, 0.1f); } } } } } |
Let me know if this works for you.
Thanks
Join us on Discord: https://discord.gg/97q2Rjh