The seeing function using a graph-based system

We will start the recipes oriented to use graph-based logic in order to simulate sense. Again, we start by developing the sense of vision.

Getting ready

It is important to have grasped the chapter regarding path finding in order to understand the inner workings of the graph-based recipes.

How to do it…

We will just implement a new file:

  1. Create the class for handling vision:
    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    
    public class VisorGraph : MonoBehaviour
    {
        public int visionReach;
        public GameObject visorObj;
        public Graph visionGraph;
    }
  2. Validate the visor object in case the com:
    void Start()
    {
        if (visorObj == null)
            visorObj = gameObject;
    }
  3. Define and start building the function for detecting the visibility of a given set of nodes:
    public bool IsVisible(int[] visibilityNodes)
    {
        int vision = visionReach;
        int src = visionGraph.GetNearestVertex(visorObj);
        HashSet<int> visibleNodes = new HashSet<int>();
        Queue<int> queue = new Queue<int>();
        queue.Enqueue(src);
    }
  4. Implement a Breadth-First Search algorithm:
    while (queue.Count != 0)
    {
        if (vision == 0)
            break;
        int v = queue.Dequeue();
        List<int> neighbours = visionGraph.GetNeighbors(v);
        foreach (int n in neighbours)
        {
            if (visibleNodes.Contains(n))
                continue;
            queue.Enqueue(v);
            visibleNodes.Add(v);
        }
    }
  5. Compare the set of visible nodes with the set of nodes reached by the vision system:
    foreach (int vn in visibleNodes)
    {
        if (visibleNodes.Contains(vn))
            return true;
    }
  6. Return false if there is no match between the two sets of nodes:
    return false;

How it works…

The recipe uses the Breadth-First Search algorithm in order to discover nodes within its vision reach, and then compares this set of nodes to the set where agents reside.

The input array is computed outside, and it's out of the scope of this recipe because it relies on pinpointing, for example, the position of each agent or object that needs to be checked visibly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.167.195