top of page

Shortest Path on Click


Use this script on the player, it's called Patrol.

 

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class Patrol : MonoBehaviour {

public Waypoint start;

public Waypoint end;

public float speed;

public float threshold;

public Waypoint wp1, wp2, wp3, wp4;

private List<Waypoint> path;

private int current;

Vector3 newPosition;

// Use this for initialization

void Start()

{

newPosition = transform.position;

InvokeRepeating("doDepth", 0, 4.8f);

}

// Update is called once per frame

void Update()

{

if (Input.GetMouseButtonUp(0))

{

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

RaycastHit hit;

if (Physics.Raycast(ray, out hit))

{

//print (hit.collider.transform.name);

//print (hit.point);

newPosition = hit.point;

}

float distance1 = Vector3.Distance(wp1.transform.position, newPosition);

float distance2 = Vector3.Distance(wp2.transform.position, newPosition);

float distance3 = Vector3.Distance(wp3.transform.position, newPosition);

float distance4 = Vector3.Distance(wp4.transform.position, newPosition);

if (distance1 <= distance2 && distance1 <= distance3 && distance1 <= distance4)

{

this.start = wp1;

this.end = wp4;

}

else if (distance2 <= distance1 && distance2 <= distance3 && distance2 <= distance4)

{

this.start = wp2;

this.end = wp1;

}

else if (distance3 <= distance1 && distance3 <= distance2 && distance3 <= distance4)

{

this.start = wp3;

this.end = wp2;

}

else

{

this.start = wp4;

this.end = wp3;

}

doDepth();

}

if (path != null && current != path.Count)

{

transform.LookAt(path[current].transform);

transform.Translate(transform.forward * Time.deltaTime * speed, Space.World);

float distance = Vector3.Distance(transform.position, path[current].transform.position);

//print ("distance" + distance);

if (distance < threshold)

{

current++;

}

}

}

void doDepth(){

List<Waypoint> resultado = PathFinding.Depthwise(start, end);

path = resultado;

current = 0;

}

}

 

bottom of page