using UnityEngine; using System.Collections; using Pathfinding; public class AgentAStar : MonoBehaviour { public GameObject particle; protected Seeker seeker; protected Animator animator; protected Locomotion locomotion; protected Object particleClone; // The calculated path public Path path; // The AI's speed per second public float speed = 1; // The max distance from the AI to a waypoint for it to continue to the next waypoint public float nextWaypointDistance = 3; // The waypoint we are currently moving towards private int currentWaypoint = 0; // Use this for initialization void Start () { seeker = GetComponent(); animator = GetComponent(); locomotion = new Locomotion(animator); particleClone = null; } protected void SetDestination() { // Construct a ray from the current mouse coordinates var ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit = new RaycastHit(); if (Physics.Raycast(ray, out hit)) { if (particleClone != null) { GameObject.Destroy(particleClone); particleClone = null; } // Create a particle if hit Quaternion q = new Quaternion(); q.SetLookRotation(hit.normal, Vector3.forward); particleClone = Instantiate(particle, hit.point, q); //$$ agent.destination = hit.point; seeker.StartPath (transform.position, hit.point, OnPathComplete); } } public void OnPathComplete (Path p) { Debug.Log ("Yey, we got a path back (error = " + p.error + ")\n"); if (!p.error) { path = p; // Reset the waypoint counter currentWaypoint = 0; } } protected void SetupAgentLocomotion() { if (path == null) { locomotion.Do(0, 0); if (particleClone != null) { GameObject.Destroy(particleClone); particleClone = null; } } else { // Direction to the next waypoint Vector3 desiredVelocity = (path.vectorPath[currentWaypoint] - transform.position).normalized; // Check if we are close enough to the next waypoint // If we are, proceed to follow the next waypoint if (Vector3.Distance (transform.position,path.vectorPath[currentWaypoint]) < nextWaypointDistance) { currentWaypoint++; if (currentWaypoint < path.vectorPath.Count) { Debug.Log ("Move to next waypoint : " + currentWaypoint + "\n"); } else { Debug.Log ("End Of Path Reached\n"); path = null; } } desiredVelocity *= speed ; Vector3 velocity = Quaternion.Inverse(transform.rotation) * desiredVelocity; // desiredVelocity float angle = Mathf.Atan2(velocity.x, velocity.z) * 180.0f / 3.14159f; locomotion.Do(speed, angle); } } void OnAnimatorMove() { transform.Translate (animator.deltaPosition, Space.World); transform.rotation = animator.rootRotation; } // Update is called once per frame void Update () { if (Input.GetButtonDown ("Fire1")) { if (path != null) { Debug.Log ("Path canceled (currentWaypoint = " + currentWaypoint + "/" + path.vectorPath.Count + ")\n"); path = null; } SetDestination(); } SetupAgentLocomotion(); } }