Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- using System.Collections.Generic;
- public class Seeker : MonoBehaviour
- {
- public List<Node> path = new List<Node>();
- public int cordsX, cordsY;
- Transform tr;
- void Start()
- {
- tr = transform;
- cordsX = Mathf.RoundToInt(tr.position.x);
- cordsY = Mathf.RoundToInt(tr.position.z);
- }
- public Animator anim;
- void LateUpdate()
- {
- if (path.Count > 1)
- {
- for (int i = 0; i < path.Count - 1; i++)
- {
- Debug.DrawLine(path[i].cords, path[i + 1].cords, Color.blue);
- }
- transform.position = Vector3.Lerp(transform.position, path[1].cords, Time.deltaTime * 4);
- if (Vector3.Distance(transform.position, path[1].cords) < 0.4f)
- {
- //stops units if their target is occupied. doesn't work perfectly
- if (path[1].occupied == null)
- {
- if (path.Count <= 2)
- {
- path[0].occupied = this;
- }
- else
- {
- path.RemoveAt(0);
- }
- }
- else
- {
- Node cur = path[0];
- path = new List<Node>();
- path.Add(cur);
- path[0].occupied = this;
- }
- cordsX = Mathf.RoundToInt(path[0].cords.x);
- cordsY = Mathf.RoundToInt(path[0].cords.z);
- }
- if (path.Count > 2)
- {
- transform.rotation = Quaternion.LookRotation(path[1].cords - transform.position);
- if (anim != null)
- {
- anim.SetFloat("Speed", 1);
- }
- }
- else
- {
- anim.SetFloat("Speed", 0);
- }
- }
- if (Input.GetMouseButtonDown(0))
- {
- RaycastHit hit;
- Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
- if (Physics.Raycast(ray, out hit))
- {
- GeneratePathTo(hit.point);
- }
- }
- if (Input.GetMouseButtonDown(1))
- {
- RaycastHit hit;
- Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
- if (Physics.Raycast(ray, out hit))
- {
- if (PathfindingMap.Instance.nodeTypes.Length >= 2)
- {
- NodeTemplate temp = PathfindingMap.Instance.nodeTypes[1];
- Vector3 pos = new Vector3(Mathf.RoundToInt(hit.point.x), 0, Mathf.RoundToInt(hit.point.z));
- Node node = PathfindingMap.VecToNode(pos);
- node.inWorld.GetComponent<MeshRenderer>().material = temp.mat;
- node.cost = temp.Cost;
- node.enterable = temp.enterable;
- PathfindingMap.Instance.grid.walls.Add(node.cords);
- }
- }
- }
- }
- public void GeneratePathTo(Vector3 _pos)
- {
- int x = Mathf.RoundToInt(_pos.x);
- int y = Mathf.RoundToInt(_pos.z);
- Vector3 pos = new Vector3(x, 0, y);
- List<Vector3> _path = new List<Vector3>();
- if (PathfindingMap.Instance.grid.Passable(pos))
- {
- AStarSearch search = new AStarSearch(PathfindingMap.Instance.grid, new Vector3(cordsX, 0, cordsY), pos);
- _path = search.FindShortestPath();
- }
- path = new List<Node>();
- for (int i = 0; i < _path.Count; i++)
- {
- path.Add(PathfindingMap.VecToNode(_path[i]));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement