Advertisement
DCSquid

Pathfinder

Mar 25th, 2017
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.64 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5.  
  6. public class PathFinder : MonoBehaviour {
  7.     public float speed=10;
  8.     public PathSite currentSite;
  9.     public Queue<PathSite> currentRoute=new Queue<PathSite>();
  10.     public PathSite destination;
  11.  
  12.     public double costEstimate(Node n1, Node n2){
  13.         if(n1 is PathSite && n2 is PathSite){
  14.             PathSite n1site=n1 as PathSite;
  15.             PathSite n2site=n2 as PathSite;
  16.             return (n1site.GetComponent<Transform>().position-n2site.GetComponent<Transform>().position).magnitude;
  17.         }
  18.  
  19.         return 0;
  20.     }
  21.  
  22.     public void routeTo(PathSite destination){
  23.         if (currentSite!=null) {
  24.             Debug.Log("routing");  
  25.             List<PathSite> route=PathFinding.Astar(currentSite, destination, costEstimate).Cast<PathSite>().ToList();
  26.             currentRoute=new Queue<PathSite>(route);
  27.             this.destination=destination;
  28.         }
  29.     }
  30.  
  31.     // Use this for initialization
  32.     void Start () {
  33.  
  34.     }
  35.    
  36.     // Update is called once per frame
  37.     void Update () {
  38.         if(currentSite!=null){
  39.             //check if you're at the current site
  40.             double dist=((Vector2)currentSite.transform.position-(Vector2)transform.position).magnitude;
  41.             if(dist<(.01*speed)){//TODO <- this is kludgy, need a better way to define closeness
  42.                 //if you are and there are more sites in the route, then go to the next site
  43.                 if (currentRoute.Count!=0){
  44.                     currentSite=currentRoute.Dequeue();
  45.                 }
  46.             }else{
  47.                 //if not, move towards the current site
  48.                 //transform.LookAt(currentSite.transform);
  49.                 Vector2 dir=(currentSite.transform.position-transform.position);
  50.                 transform.Translate(dir.normalized*(speed*Time.deltaTime));
  51.             }
  52.         }
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement