Our agent is just consist of a capsule and a cube parented to it. The box collider on the cube was removed.
And also, I make the main camera parented to our agent. Just position it till you can achieve a third person camera look.
Then, set up some nodes/waypoints to our scene. Our nodes are just sphere without any collider. Create an empty Game Object and name it Path. Make all of our nodes parented to that Path.
Our Path script has only an array of Transform and a function to get some certain of node position.
// script by @effendiilham using UnityEngine; using System.Collections; public class Path : MonoBehaviour { public Transform[] nodes; public Vector3 GetNodePos(int id){ return nodes[id].position; } }
Attach the Path script to our Path game object on the scene. Then drag each nodes to it.
Then we are ready to create our Agent script.
// script by @effendiilham using UnityEngine; using System.Collections; public class Agent : MonoBehaviour { public Path path; public float reachDistance = 1f; public bool drawGizmos = false; public float speed = 5f; public float rotSpeed = 10f; private int currentNodeID = 0; void Start () { } void Update () { Vector3 dest = path.GetNodePos (currentNodeID); Vector3 offset = dest - transform.position; if (offset.sqrMagnitude > reachDistance) { offset = offset.normalized; transform.Translate (offset * speed * Time.deltaTime, Space.World); Quaternion lookRot = Quaternion.LookRotation(offset); transform.rotation = Quaternion.Slerp(transform.rotation, lookRot, rotSpeed * Time.deltaTime); } else { ChangeDestNode(); } } void ChangeDestNode(){ currentNodeID++; if(currentNodeID >= path.nodes.Length){ currentNodeID = 0; } } void OnDrawGizmos() { if (drawGizmos) { Gizmos.color = Color.red; Gizmos.DrawLine(transform.position, path.GetNodePos (currentNodeID)); } } }
The script above will make our agent follow the current node, and if he is close enough, he will change the destination node to the next node. Now attach the Agent script to our agent on the scene. Don't forget to drag the Path to Agent script.
You can check the Draw Gizmos option on Agent script to see the current node which is our agent following.
You can download the project file here. That's it. Thank you for reading this tutorial. See you soon on the next post. ;)
4 comment(s):
Thank you :)
This was a great help. Thanks
Can this be used as human traffic in a game?
Post a Comment
feel free to write your comment here.. :)