Search code examples
c#unity-game-engine3d

Collider.isTouching for 3D colliders


if (colliderBox.isTouching (col) && col.CompareTag("barrier")) {
        score++;
        this.GetComponent<Renderer> ().material.color = col.GetComponent<Renderer> ().material.color;
    }

    if (spriteBox.IsTouching(col) && col.CompareTag("barrier") ) {
        Debug.Log (col);
        Debug.Log (colliderBox);
        SceneManager.LoadScene (mainMenu);
    }

Currently in my code, I was using a onTriggerEnter, to detect a collision with an object called 'barrier', but I have had to replace my 2d spriteBox and 2d colliderBox with 3D objects, and now isTouching is not a property of 3D colliders. I can not find a simple replacement. What can I replace them with?


Solution

  • There is no equivalent version of the isTouching function for 3D collision but you can roll your own. When OnTriggerEnter, store both colliders involved in a collection. When OnTriggerExit is called, check for both colliders involved and if already exit in the collection, remove them from the collection. This is what I am doing in this post with the CollisionDetection script.

    Attach the CollisionDetection script to the objects that will be colliding.

    To check if Collider is touching another Collider, change:

    if (colliderBox.isTouching (col) && col.CompareTag("barrier")) { }
    

    to:

    if (CollisionDetection.IsTouching (colliderBox.gameObject, col.gameObject) && col.CompareTag("barrier")) {  }
    

    You can also add ExtensionMethod for the CollisionDetection class:

    public static class ExtensionMethod
    {
        public static bool IsTouching(this Collider collider, Collider otherCollider)
        {
            return CollisionDetection.IsTouching(collider.gameObject, otherCollider.gameObject);
        }
    
        public static bool IsTouching(this GameObject collider, GameObject otherCollider)
        {
            return CollisionDetection.IsTouching(collider, otherCollider);
        }
    }
    

    Now, your if (colliderBox.isTouching (col) && col.CompareTag("barrier")) code should work without changes assuming that colliderBox is a type of Collider or GameObject.