Another sense we're going to implement is Touch.cs
, which is triggered when the player entity is within a certain area near the AI entity. Our AI character has a box collider component and its IsTrigger
flag is on.
We need to implement the OnTriggerEnter
event that will be fired whenever the collider component is collided with another collider component. Since our tank entity also has a collider and rigid body components, collision events will be raised as soon as the colliders of the AI character and player tank are collided.
The code in the Touch.cs
file can be shown as follows:
using UnityEngine; using System.Collections; public class Touch : Sense { void OnTriggerEnter(Collider other) { Aspect aspect = other.GetComponent<Aspect>(); if (aspect != null) { //Check the aspect if (aspect.aspectName == aspectName) { print("Enemy Touch Detected"); } } } }
We implement the OnTriggerEnter
event to be fired whenever the collider component is collided with another collider component. Since our tank entity also has a collider and the rigid body components, collision events will be raised as soon as the colliders of the AI character and the player tank are collided. Our trigger can be seen in the following screenshot:
The preceding screenshot shows the box collider of our enemy AI that we'll use to implement the touch sense. In the following screenshot, we see how our AI character is set up:
Inside the OnTriggerEnter
method, we access the aspect component of the other collided entity and check whether the name of the aspect is the aspect this AI character is looking for. And, for demo purposes, we just print out that the enemy aspect has been detected by touch sense. We can also implement other behaviors in real projects; maybe the player will turn over to an enemy and start chasing, attacking, and so on.