Collision and sound issues

Didn’t really know which section would be the best to put this in.

Anyways, I have a hammer on my main character, and it is suppose to play my sound clip under 2 conditions.

  1. if the animation is playing.
  2. if collisions are detected.

It works, kinda. It should be playing even if its clipping through the object but for whatever reason it only works if the collision isn’t happening prior to the swing (See pictures below)

Here is the code that is attached to my hammer. The hammer is a child to the main camera, which is a child to the player.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Hammer : MonoBehaviour
{
    public bool isSwinging;
    private AudioSource hammerSource;
    private Animation anim;

    void Awake()
    {
        anim = GetComponent<Animation> ();
        hammerSource = GetComponent<AudioSource> ();
        isSwinging = false;
    }

    void Update()
    {
        if (Input.GetMouseButton (0)) {
            anim.Play ();
            isSwinging = true;
        }
        else if (Input.GetMouseButtonUp (0))
        {
            isSwinging = false;
        }
    }


    void OnTriggerEnter(Collider col)
    {
        if (col.CompareTag ("Phys"))
        {
            if (isSwinging)
            {
                Debug.Log ("Hit");
            }
        }
    }

}

Here are 2 examples

Fig 1 - Collider box not touching the cubes collider box prior to animation. This works.
Fig 2 - Collider box inside of cube prior to animation. This does not work.

3034804--227091--1.PNG
3034804--227092--2.PNG

OnTriggerEnter() only happens once - when the collider enters another collider. If you stay in the collider after that it won’t trigger again. The next thing that will trigger is OnTriggerExit() when the collider leaves.

If you want to check continuously you could use OnTriggerStay() instead. That method triggers once the collider enters and then in every frame again until it leaves. Of course that’s a bit more costly since it’s checking in every physics update, but it’s a valid solution and if you need it to check all the time you’ll probably want to use it.

Remember that you need to make sure the sound only plays once then, so you don’t end up with a .Play() every frame.