top of page
Search

Finding the shortest path (Automatic)

  • Writer: Oscar Acosta Mendoza
    Oscar Acosta Mendoza
  • Oct 23, 2017
  • 1 min read

This code always finds the shortest path of a graph, it does it automatically.

 

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class PathTest : MonoBehaviour {

public Waypoint start;

public Waypoint end;

public float speed;//3

public float threshold;//0.05

public Waypoint[] allNodes; //for search

private List<Waypoint> path;

private List<Waypoint> result;

private int currentNode;

private bool Active = true;

// Use this for initialization

void Start () {

result = Pathfinding.Breadthwise (start, end);

path = result;

}

// Update is called once per frame

void Update (){

//Para ir al nodo cuando se hace clic sobre el

if (Input.GetMouseButtonUp (0)) {

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

RaycastHit hit;

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

transform.LookAt(hit.point);

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

for (int i = 0; i < allNodes.Length; i++)

{

if(allNodes[i].name.Equals(hit.collider.transform.name))

{

start = allNodes[i];

break;

}

}

result = Pathfinding.Breadthwise(start, end);

path = result;

currentNode = 0;

}

}

//Movimiento sobre el grafo

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

{

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

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

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

if (distance < threshold)

{

currentNode++;

}

}

//Para reiniciar el patrulleo

if(currentNode == path.Count)

{

currentNode = 0;

}

}

}

 

If you don't want it to go to the nearest node by doing a click then simply eliminate the if condition.

AKA.... this part:

//Para ir al nodo cuando se hace clic sobre el

if (Input.GetMouseButtonUp (0)) {

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

RaycastHit hit;

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

transform.LookAt(hit.point);

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

for (int i = 0; i < allNodes.Length; i++)

{

if(allNodes[i].name.Equals(hit.collider.transform.name))

{

start = allNodes[i];

break;

}

}

 

Kommentare


©2017 BY UNITY 101. PROUDLY CREATED WITH WIX.COM

  • Facebook
  • Twitter
  • LinkedIn
bottom of page