Continuous movement with waypoint systems, and NavMesh agent
Hello, I'm creating a 3D game where I want to make my player gameobjects continuously move around to a set amount of waypoints in a random sequence. I take advantage of a waypoint system made up of empty gameobjects scattered around my scene. I then have a set amount of player gameobjects that move towards these waypoints based upon a random number, and using the NavMesh Agent component for the movement. I have a box collider set upon each of these waypoints, and I check if OnTriggerEnter
on these waypoints to once more calculate a new random destination for the player object to travel to. This code works quite well I'm experiencing some jittering once in a while on the player objects.
I think that there might be a better way to:
Check if a player and waypoint have collided (not using a collider for the waypoints)
Then based upon that, choose a new random waypoint for that specific player to travel to.
Here is the Walking.cs
script that I have attached to each of my player gameobjects:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Walking : MonoBehaviour {
public GameObject[] waypoints;
public int random;
public UnityEngine.AI.NavMeshAgent player;
void Start() {
waypoints = GameObject.FindGameObjectsWithTag("Waypoint");
random = Random.Range(0, waypoints.Length);
player = GetComponent<UnityEngine.AI.NavMeshAgent>();
player.destination = waypoints[random].transform.position;
}
void OnTriggerEnter(Collider waypoint) {
random = Random.Range(0, waypoints.Length);
if (waypoint.gameObject.tag == "Waypoint") {
player.destination = waypoints[random].transform.position;
Debug.Log("Triggered!");
}
}
}