The smelling function using a graph-based system

In this recipe, we take a mixed approach to tag vertices with a given odor particle that collides with it.

Getting ready

The vertices should have a broad collider attached so that they catch the odor particles nearby.

How to do it…

  1. Add the following member variable to the odor-particle script to store its parent ID:
    public int parent;
  2. Create the new odor-enabled class, deriving from the original vertex:
    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    
    public class VertexOdour : Vertex
    {
        private Dictionary<int, OdourParticle> odourDic;
    }
  3. Initialize the odor dictionary in the proper function:
    public void Start()
    {
        odourDic = new Dictionary<int, OdourParticle>();
    }
  4. Add the odor to the vertex's dictionary:
    public void OnCollisionEnter(Collision coll)
    {
        OdourOdourParticle op;
        op = coll.gameObject.GetComponent<OdourParticle>();
        if (op == null)
            return;
        int id = op.parent;
        odourDic.Add(id, op);
    }
  5. Remove the odor from the vertex's dictionary:
    public void OnCollisionExit(Collision coll)
    {
        OdourParticle op;
        op = coll.gameObject.GetComponent<OdourParticle>();
        if (op == null)
            return;
        int id = op.parent;
        odourDic.Remove(id);
    }
  6. Implement the function for checking if there is any odor tagged:
    public bool HasOdour()
    {
        if (odourDic.Values.Count == 0)
            return false;
        return true;
    }
  7. Implement the function for checking if a given type of odor is indexed in the vertex:
    public bool OdourExists(int id)
    {
        return odourDic.ContainsKey(id);
    }

How it works…

The odor particles collide with the vertices, being indexed in their odor dictionary. From that point on, our agents can check whether a given odor is registered in a vertex nearby.

See also

  • Chapter 2, Navigation recipe, BFS and graph construction
..................Content has been hidden....................

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