Friday, January 25, 2019

unity - How can I determine which Trigger is hit?


I have a GameObject. It has 3 BoxCollider2Ds:




  1. Body Collider - Not a trigger - Determines if body is hit

  2. Weapon Collider - Trigger - Determines if weapon is hit

  3. Vision Collider - Trigger - Determines what the GameObject sees


I can tell the Body Collider apart from the other colliders, because it has a different method (OnCollisionEnter2D). However, I cannot tell the Weapon Collider and Vision Collider apart. They both access the same method (OnTriggerEnter2D), and pass in the collider they are hitting. I cannot determine which one is hit.


I could put each trigger on a separate child GameObject, and send a message to the parent, but this is very slow and feels messy to me. What is the best way I can determine which trigger I am hitting?




From the Unity Docs for reference:


using UnityEngine;

using System.Collections;

public class ExampleClass : MonoBehaviour {
public bool characterInQuicksand;
void OnTriggerEnter2D(Collider2D other) {
characterInQuicksand = true;
}
}

Answer



You might have some success checking the Collider2D.IsTouching method in your OnTriggerEnter.



void OnTriggerEnter2D(Collider2D col)
{
if (weaponCollider.IsTouching(col)) { /* Weapon */ }
if (sightCollider.IsTouching(col)) { /* Sight */ }
}

IsTouching is polled against the last physics update so it should be pretty light weight.


However, if your colliders overlap, it might be best to process the triggers during OnLateUpdate or keep tabs on the touching colliders separately.


HashSet collidesWithWeapon;
void OnTriggerEnter2D(Collider2D col)

{
if (weaponCollider.IsTouching(col)
&& !collidesWithWeapon.Contains(col.GetInstanceID()))
{
collidesWithWeapon.Add(col.GetInstanceID());
// Weapon stuff
}
}

void OnTriggerExit2D(Collider2D col)

{
if (!weaponCollider.IsTouching(col)) collidesWithWeapon.Remove(col.GetInstanceID());
}

I'm pretty sure there are other curve balls along the way, but hope this helps forward. Adding the colliders to other GameObjects might help too, but I think trigger events cascade top to bottom or something similar. Can't remember what it was exactly, though... Whatever it was, I've made it a practice to check the IsTouching() if the hierarchy contains more than one collider.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...