Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using Pathfinding;
- public class Ghost : MonoBehaviour {
- public Rigidbody2D body2D;
- // The point to move to
- public Vector3 targetPosition;
- private Seeker seeker;
- // The calculated path
- public Path path;
- // 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;
- // How often to recalculate the path (in seconds)
- public float repathRate = 2f;
- private float lastRepath = -9999;
- public void Start () {
- seeker = GetComponent<Seeker>();
- body2D = GetComponent<Rigidbody2D> ();
- body2D.freezeRotation = true;
- targetPosition = GameObject.FindGameObjectWithTag ("Target").transform.position;
- }
- public void OnPathComplete (Path p) {
- Debug.Log("A path was calculated. Did it fail with an error? " + p.error);
- if (!p.error) {
- path = p;
- // Reset the waypoint counter so that we start to move towards the first point in the path
- currentWaypoint = 0;
- }
- }
- public void FixedUpdate () {
- if (Time.time - lastRepath > repathRate && seeker.IsDone()) {
- lastRepath = Time.time+ Random.value*repathRate*0.5f;
- // Start a new path to the targetPosition, call the the OnPathComplete function
- // when the path has been calculated (which may take a few frames depending on the complexity)
- Debug.Log("Seeker update");
- seeker.StartPath(transform.position, targetPosition, OnPathComplete);
- }
- if (path == null) {
- // We have no path to follow yet, so don't do anything
- return;
- }
- if (currentWaypoint > path.vectorPath.Count) return;
- if (currentWaypoint == path.vectorPath.Count) {
- Debug.Log("End Of Path Reached");
- currentWaypoint++;
- return;
- }
- // Direction to the next waypoint
- Vector3 dir = (path.vectorPath[currentWaypoint]-transform.position).normalized;
- body2D.velocity = dir;
- // The commented line is equivalent to the one below, but the one that is used
- // is slightly faster since it does not have to calculate a square root
- //if (Vector3.Distance (transform.position,path.vectorPath[currentWaypoint]) < nextWaypointDistance) {
- if ((transform.position-path.vectorPath[currentWaypoint]).sqrMagnitude < nextWaypointDistance*nextWaypointDistance) {
- Debug.Log("currentWayPoint: " + currentWaypoint);
- currentWaypoint++;
- return;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement