- Home /
Basic Mind Control Mechanic
So I want to create a simple mind control mechanic for a game. The control is predetermined by a script and NavPoints, and I am currently trying to use a basic patrol behavior I found here in Unity documents. What I want to happen, is when the player comes in contact with the NPC, they press a button, and that NPC will travel to the stated navpoint, but I am not having much luck. Here is the script I am tinkering around with:
using UnityEngine;
using UnityEngine.AI;
using System.Collections;
public class WorkerBehavior : MonoBehaviour {
public Transform[] points;
private int destPoint = 0;
private NavMeshAgent agent;
// Use this for initialization
void Start () {
agent = GetComponent<NavMeshAgent>();
agent.autoBraking = false;
}
void GotoNextPoint()
{
if (points.Length == 0)
return;
agent.destination = points[destPoint].position;
destPoint = (destPoint + 1) % points.Length;
}
void Update () {
}
void OnTriggerEnter(Collider other)
{
if (Input.GetKeyDown(KeyCode.KeypadEnter))
{
GotoNextPoint();
}
}
}
I do understand there is some unnecessary code here. For instance, I have no real need to reset my nav points, as this NPC will only have one destination after it is activated. This patrol behavior may even be useless for what I am trying to do. Any advice would be helpful though, and I thank you in advance.
Answer by Dwarneke · Oct 03, 2018 at 09:55 PM
Never mind everyone, I figured it out. If anyone is interested however I'll leave my solution here:
using UnityEngine;
using UnityEngine.AI;
using System.Collections;
public class WorkerBehavior : MonoBehaviour {
public Transform[] points;
private int destPoint = 0;
private NavMeshAgent agent;
// Use this for initialization
void Start () {
agent = GetComponent<NavMeshAgent>();
}
void GotoNextPoint()
{
// Returns if no points have been set up
if (points.Length == 0)
return;
// Set the agent to go to the currently selected destination.
agent.destination = points[destPoint].position;
// Choose the next point in the array as the destination,
// cycling to the start if necessary.
destPoint = (destPoint + 1) % points.Length;
}
// Update is called once per frame
void Update () {
}
void OnTriggerStay(Collider other)
{
Debug.Log("Entered");
if (Input.GetKeyDown(KeyCode.Return))
{
Debug.Log("Return pressed");
GotoNextPoint();
}
}
}
I made some adjustments off of the script I found here: https://docs.unity3d.com/Manual/nav-AgentPatrol.html
This script added to a gameobject, with a collider, will cause the gameobject to move toward a navpoint, when you come in contact with it and press return.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
NavMeshAgent Move experience? 0 Answers
NavMeshAgents rotate to target but do not move 1 Answer
Does NavMeshAgent disable a gameObject's collider? 1 Answer
Nav Mesh problem~ I need help! 0 Answers