Search Unity

Trigger Sound on Terrain -> Tree Collider

Discussion in 'Physics' started by matthewkris, Feb 2, 2021.

  1. matthewkris

    matthewkris

    Joined:
    Dec 23, 2020
    Posts:
    1
    I'm in the process of recreating some old scenes and am adding trees via the terrain editor. Collision is working fine on the trees but I'm running into an issue where I can't trigger anything. Any hit registers as a hit with the terrain instead of the tree.

    Is there any way to determine if we've hit a tree so I can trigger the appropriate audio?
     
  2. AlTheSlacker

    AlTheSlacker

    Joined:
    Jun 12, 2017
    Posts:
    326
  3. hedgefield

    hedgefield

    Joined:
    Jan 1, 2014
    Posts:
    39
    I tried the same thing but unfortunately even with preserving tree prototypes and setting different tags and layers I could not get it to work.
     
  4. AlTheSlacker

    AlTheSlacker

    Joined:
    Jun 12, 2017
    Posts:
    326
    OK pretty lazy alternative...

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Bump : MonoBehaviour
    6. {
    7.     [SerializeField] private float tolerance = 0.1f;
    8.  
    9.     void OnCollisionEnter(Collision collision)
    10.     {
    11.         if (collision.gameObject.name == "Terrain") {
    12.             Vector3 hitLocation = collision.contacts[0].point;
    13.             float terrainHeight = Terrain.activeTerrain.SampleHeight(hitLocation);
    14.             if (hitLocation.y - tolerance > terrainHeight) Debug.Log("Tree");
    15.             else Debug.Log("Ground");
    16.         }
    17.     }
    18. }