Smelling is one of the trickiest senses to translate from the real to the virtual world. There are several techniques, but most of them are inclined to the use of colliders or graph logic.
Smelling can be simulated by computing a collision between an agent and odor particles scattered throughout the game level.
As with the other recipes based on colliders, we will need collider components attached to every object that is to be checked, and rigid body components attached to either emitters or receivers.
We will develop the scripts for representing odor particles and agents that are able to smell:
using UnityEngine; using System.Collections; public class OdourParticle : MonoBehaviour { public float timespan; private float timer; }
Start
function for proper validations:void Start() { if (timespan < 0f) timespan = 0f; timer = timespan; }
void Update() { timer -= Time.deltaTime; if (timer < 0f) Destroy(gameObject); }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class Smeller : MonoBehaviour { private Vector3 target; private Dictionary<int, GameObject> particles; }
void Start() { particles = new Dictionary<int, GameObject>(); }
public void OnTriggerEnter(Collider coll) { GameObject obj = coll.gameObject; OdourParticle op; op = obj.GetComponent<OdourParticle>(); if (op == null) return; int objId = obj.GetInstanceID(); particles.Add(objId, obj); UpdateTarget(); }
public void OnTriggerExit(Collider coll) { GameObject obj = coll.gameObject; int objId = obj.GetInstanceID(); bool isRemoved; isRemoved = particles.Remove(objId); if (!isRemoved) return; UpdateTarget(); }
private void UpdateTarget() { Vector3 centroid = Vector3.zero; foreach (GameObject p in particles.Values) { Vector3 pos = p.transform.position; centroid += pos; } target = centroid; }
public Vector3? GetTargetPosition() { if (particles.Keys.Count == 0) return null; return target; }
Just like the hearing recipe based on colliders, we use the trigger colliders in order to register odor particles in an agent's perception (implemented using a dictionary). When a particle is included or removed, the odor centroid is computed. However, we implement a function for retrieving that centroid because when no odor particle is registered, the internal centroid position is not updated.
Particle emission logic is left behind to be implemented according to our game's needs, and it's basically instantiating odor-particle prefabs. Also, it is recommended that you attach the rigid-body components to the agents. Odor particles are prone to be massively instantiated, reducing the game's performance.
18.223.237.131