I want to know how I can make this game object follow the specified path in unity
1 Answer
Take a look at the Navigation components. You can add a NavMeshAgent to a GameObject and control with a script the path he should walk.
You can easily do in this script:
NavMeshAgent navmAgent;
navmAgent = GetComponent<NavMeshAgent>();
navmAgent.SetDestination([your destination]);
The NavAgent will search for the fastest way to this destination, if you want a more determined path, you could use a set of "RallyPoints".
This is the example from the Unity tutorial, with a little adjustment:
// Patrol.cs
using UnityEngine;
using System.Collections;
public class Patrol : MonoBehaviour {
public Transform[] points;
private int destPoint = 0;
private NavMeshAgent agent;
void Start () {
agent = GetComponent<NavMeshAgent>();
// Disabling auto-braking allows for continuous movement
// between points (ie, the agent doesn't slow down as it
// approaches a destination point).
agent.autoBraking = false;
GotoNextPoint();
}
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;
//Just choosing the next point (different to tutorial)
destPoint = Mathf.Max(points.Length-1, ++destPoint);
}
void Update () {
// Choose the next destination point when the agent gets
// close to the current one.
if (agent.remainingDistance < 0.5f)
GotoNextPoint();
}
}
So bascially create a set of points, which determine your path. Give your GameObject a NavMeshAgent and a script which tells the NavMeshAgent to walk aloing your points, similiar to the code above.
If you don't want to use the NavMesh-approach, then you could just interpolate the path and manually update the position of your GameObject.