Unity.C#.Помощь с графиком на основе приложенных скриптов

Программирование на Юнити.

Unity.C#.Помощь с графиком на основе приложенных скриптов

Сообщение Newer 10 июл 2020, 17:02

Привет ! Мне нужно создать график по которому объект будет находить кратчайший путь до финиша
Но я не знаю как добавить узлы и ребра графика в скрипте GraphBuild
Оригинал задания ( "Add the code to the script as indicated by the comments in the Awake method.Make sure you add the Start object, the End object, and all the Waypoint objects to the graph. You'll probably find the tags for those objects useful as you do that.
Add all the edges to the graph, making sure you only add an edge between two nodes if they're within 3.5 units horizontally and 3 units vertically of each other. Make sure the weight of an edge is set to the distance between the two nodes. ")
Скрипт GraphBuild
Синтаксис:
Используется csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


/// <summary>
/// Builds the graph
/// </summary>
public class GraphBuilder : MonoBehaviour
{      
    static Graph<Waypoint> graph;

    /// <summary>
    /// Awake is called before Start
    /// </summary>
    void Awake()
    {
        graph = new Graph<Waypoint>();

        // add nodes (all waypoints, including start and end) to graph  

        // add edges to graph

    }

    /// <summary>
    /// Gets the graph
    /// </summary>
    /// <value>graph</value>
    public static Graph<Waypoint> Graph
    {
        get { return graph; }
    }

}

Скрипты , которыми нужно воспользоваться

Graph :
Синтаксис:
Используется csharp
using System;
using System.Collections.Generic;

/// <summary>
/// A graph
/// </summary>
/// <typeparam name="T">type of values stored in graph</typeparam>
public class Graph<T>
{
    #region Fields

    List<GraphNode<T>> nodes = new List<GraphNode<T>>();

    #endregion

    #region Constructor

    /// <summary>
    /// Constructor
    /// </summary>
    public Graph()
    {
    }

    #endregion

    #region Properties

    /// <summary>
    /// Gets the number of nodes in the graph
    /// </summary>
    public int Count
    {
        get { return nodes.Count; }
    }

    /// <summary>
    /// Gets a read-only list of the nodes in the graph
    /// </summary>
    public IList<GraphNode<T>> Nodes
    {
        get { return nodes.AsReadOnly(); }
    }

    #endregion

    #region Methods

    /// <summary>
    /// Clears all the nodes from the graph
    /// </summary>
    public void Clear()
    {
        // remove all the neighbors from each node
        // so nodes can be garbage collected
        foreach (GraphNode<T> node in nodes)
        {
            node.RemoveAllNeighbors();
        }

        // now remove all the nodes from the graph
        for (int i = nodes.Count - 1; i >= 0; i--)
        {
            nodes.RemoveAt(i);
        }
    }

    /// <summary>
    /// Adds a node with the given value to the graph. If a node
    /// with the same value is in the graph, the value
    /// isn't added and the method returns false
    /// </summary>
    /// <param name="value">value to add</param>
    /// <returns>true if the value is added, false otherwise</returns>
    public bool AddNode(T value)
    {
        if (Find(value) != null)
        {
            // duplicate value
            return false;
        }
        else
        {
            nodes.Add(new GraphNode<T>(value));
            return true;
        }
    }

    /// <summary>
    /// Adds a weighted edge between the nodes with the given values
    /// in the graph. If one or both of the values don't exist
    /// in the graph the method returns false. If an edge
    /// already exists between the nodes the edge isn't added
    /// and the method retruns false
    /// </summary>
    /// <param name="value1">first value to connect</param>
    /// <param name="value2">second value to connect</param>
    /// <param name="weight">weight of the edge</param>
    /// <returns>true if the edge is added, false otherwise</returns>
    public bool AddEdge(T value1, T value2, int weight)
    {
        GraphNode<T> node1 = Find(value1);
        GraphNode<T> node2 = Find(value2);
        if (node1 == null ||
            node2 == null)
        {
            return false;
        }
        else if (node1.Neighbors.Contains(node2))
        {
            // edge already exists
            return false;
        }
        else
        {
            // undirected graph, so add as neighbors to each other
            node1.AddNeighbor(node2, weight);
            node2.AddNeighbor(node1, weight);
            return true;
        }
    }

    /// <summary>
    /// Removes the node with the given value from the graph.
    /// If the node isn't found in the graph, the method
    /// returns false
    /// </summary>
    /// <param name="value">value to remove</param>
    /// <returns>true if the value is removed, false otherwise</returns>
    public bool RemoveNode(T value)
    {
        GraphNode<T> removeNode = Find(value);
        if (removeNode == null)
        {
            return false;
        }
        else
        {
            // need to remove as neighor for all nodes
            // in graph
            nodes.Remove(removeNode);
            foreach (GraphNode<T> node in nodes)
            {
                node.RemoveNeighbor(removeNode);
            }
            return true;
        }
    }

    /// <summary>
    /// Removes an edge between the nodes with the given values
    /// from the graph. If one or both of the values don't exist
    /// in the graph the method returns false
    /// </summary>
    /// <param name="value1">first value to disconnect</param>
    /// <param name="value2">second value to disconnect</param>
    /// <returns>true if the edge is removed, false otherwise</returns>
    public bool RemoveEdge(T value1, T value2)
    {
        GraphNode<T> node1 = Find(value1);
        GraphNode<T> node2 = Find(value2);
        if (node1 == null ||
            node2 == null)
        {
            return false;
        }
        else if (!node1.Neighbors.Contains(node2))
        {
            // edge doesn't exist
            return false;
        }
        else
        {
            // undirected graph, so remove as neighbors to each other
            node1.RemoveNeighbor(node2);
            node2.RemoveNeighbor(node1);
            return true;
        }
    }

    /// <summary>
    /// Finds the graph node with the given value
    /// </summary>
    /// <param name="value">value to find</param>
    /// <returns>graph node or null if not found</returns>
    public GraphNode<T> Find(T value)
    {
        foreach (GraphNode<T> node in nodes)
        {
            if (node.Value.Equals(value))
            {
                return node;
            }
        }
        return null;
    }

    #endregion
}


К объектам Waypoint прикреплен скрипт Waypoint
Синтаксис:
Используется csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// A waypoint
/// </summary>
public class Waypoint : MonoBehaviour
{
    [SerializeField]
    int id;

    /// <summary>
    /// Changes waypoint to green
    /// </summary>
    /// <param name="other">other collider</param>
    void OnTriggerEnter2D(Collider2D other)
    {

    }

    /// <summary>
    /// Gets the position of the waypoint
    /// </summary>
    /// <value>position</value>
    public Vector2 Position
    {
        get { return transform.position; }
    }

    /// <summary>
    /// Gets the unique id for the waypoint
    /// </summary>
    /// <value>unique id</value>
    public int Id
    {
        get { return id; }
    }
}
Newer
UNец
 
Сообщения: 6
Зарегистрирован: 10 июл 2020, 16:14

Re: Unity.C#.Помощь с графиком на основе приложенных скриптов

Сообщение Newer 10 июл 2020, 17:06

Я бы показал как выглядит сцена с объектами , но достигнут максимальный размер вложений
Newer
UNец
 
Сообщения: 6
Зарегистрирован: 10 июл 2020, 16:14

Re: Unity.C#.Помощь с графиком на основе приложенных скриптов

Сообщение seaman 10 июл 2020, 20:17

Сюда давно не вложить файлы/картинки. Выкладывайте на другой сайт, а сюда - ссылку.
seaman
Адепт
 
Сообщения: 8352
Зарегистрирован: 24 янв 2011, 12:32
Откуда: Самара

Re: Unity.C#.Помощь с графиком на основе приложенных скриптов

Сообщение seaman 10 июл 2020, 20:20

Как я понимаю Вы хотите, чтобы кто-то за Вас решил тестовую задачу для приема на работу в иностранную фирму.
Либо - это задача на фрилансе.

Если так - это просто нагло.
seaman
Адепт
 
Сообщения: 8352
Зарегистрирован: 24 янв 2011, 12:32
Откуда: Самара

Re: Unity.C#.Помощь с графиком на основе приложенных скриптов

Сообщение Newer 10 июл 2020, 20:28

seaman писал(а):Как я понимаю Вы хотите, чтобы кто-то за Вас решил тестовую задачу для приема на работу в иностранную фирму.
Либо - это задача на фрилансе.

Если так - это просто нагло.
seaman писал(а):Как я понимаю Вы хотите, чтобы кто-то за Вас решил тестовую задачу для приема на работу в иностранную фирму.
Либо - это задача на фрилансе.

Если так - это просто нагло.


Нет , это малая часть обучающего проекта , который я хочу разобрать для себя.
Newer
UNец
 
Сообщения: 6
Зарегистрирован: 10 июл 2020, 16:14

Re: Unity.C#.Помощь с графиком на основе приложенных скриптов

Сообщение Newer 10 июл 2020, 20:33

seaman писал(а):Сюда давно не вложить файлы/картинки. Выкладывайте на другой сайт, а сюда - ссылку.


Ссылка на изображение сцены
https://drive.google.com/file/d/1UTHTyp ... sp=sharing
Newer
UNец
 
Сообщения: 6
Зарегистрирован: 10 июл 2020, 16:14

Re: Unity.C#.Помощь с графиком на основе приложенных скриптов

Сообщение seaman 10 июл 2020, 22:30

Ну, если это обучающий проект, то там должны быть и решения. Или преподаватель, у которого можно спросить...
seaman
Адепт
 
Сообщения: 8352
Зарегистрирован: 24 янв 2011, 12:32
Откуда: Самара


Вернуться в Скрипты

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 7