- Home /
Simple NPC AI using Nav Mesh
Hi Everybody, Here is my problem. I've made a C# script to navigate a NPC(no animation yet, real simple) and if you look at my script you (should) see the problem.
public class NPCTestNav : MonoBehaviour {
NavMeshAgent agent;
public Transform Nav1;
public Transform Nav2;
public Transform Nav3;
public Transform Nav4;
int RandomValue;
// Use this for initialization
void Start ()
{
agent = GetComponent<NavMeshAgent> ();
}
// Update is called once per frame
void Update ()
{
RandomValue = Random.Range (1, 5);
Debug.Log (RandomValue);
if (RandomValue == 1)
{
//This is part of a code snippit and will wreck the code if uncommented.
//Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
Ray Position1 = new Ray (Nav1.position, Input.mousePosition);
RaycastHit hit1;
if (Physics.Raycast (Position1, out hit1, 1000))
{
agent.SetDestination (hit1.point);
}
}
if (RandomValue == 2)
{
Ray Position2 = new Ray (Nav2.position, Input.mousePosition);
RaycastHit hit2;
if (Physics.Raycast (Position2, out hit2, 1000))
{
agent.SetDestination (hit2.point);
}
}
}
}
As you can see, it assigns a new Destination every few frames. I currently have only 4 destination points, but have not got that far yet, just trying to work out two points. So, my solution just add a simple script to get the speed of the NPC and then add an && to the if asking if the avatar is moving. However, whenever I try to add the code, it always comes up as not moving???? What is up here?
EDIT: Ok so to clarify, I want an NPC that will, every frame choose randomly with a 1in4 chance a new Destination unless it is already travelling to a destination. There is four destination points, these destination points are cubes.
Answer by SkaredCreations · Dec 18, 2014 at 01:43 PM
I think this should be fine (drag on Navs all the transforms where you want the agent can walk to):
using UnityEngine;
using System.Collections;
public class NPCTestNav : MonoBehaviour {
public Transform[] Navs;
NavMeshAgent agent;
void Start ()
{
agent = GetComponent<NavMeshAgent>();
}
void Update ()
{
if (agent.velocity.magnitude == 0f)
{
agent.SetDestination(Navs[Random.Range(0, Navs.Length)].position);
}
}
}
I have updated my post to help clear up what I was trying to do.
Thanks @SkaredCreations, however after adding a walk animation I had to tweak the statement to <= rather than ==.
Your answer
