Gotta hit my bushes three times! And they shake!

bushshake
Gave my destrusctables a number of hits before they are destroyed and found a very nice piece of code for shaking them when they are hit. I love it! Now to give a little ‘bushy’ sound when whacked by the sword and it should be good!

using UnityEngine;

public class Destructable : MonoBehaviour
{
    [SerializeField] private GameObject destroyVFX;
    [SerializeField] private int hitsToDestroy = 1;
    [SerializeField] float shake_decay = 0.004f;
    [SerializeField] float shake_intensity = .1f;

    private Vector3 originPosition;
    private Quaternion originRotation;
    private float temp_shake_intensity = 0;

    void Update()
    {
        if (temp_shake_intensity > 0)
        {
            transform.position = originPosition + Random.insideUnitSphere * temp_shake_intensity;
            transform.rotation = new Quaternion(
                originRotation.x + Random.Range(-temp_shake_intensity, temp_shake_intensity) * .2f,
                originRotation.y + Random.Range(-temp_shake_intensity, temp_shake_intensity) * .2f,
                originRotation.z + Random.Range(-temp_shake_intensity, temp_shake_intensity) * .2f,
                originRotation.w + Random.Range(-temp_shake_intensity, temp_shake_intensity) * .2f);
            temp_shake_intensity -= shake_decay;
        }
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.GetComponent<DamageSource>())
        {
            hitsToDestroy--;

            if (hitsToDestroy <= 0)
            {
                Instantiate(destroyVFX, transform.position, Quaternion.identity);
                Destroy(gameObject);
            }
            else
            {
                Shake();
            }
        }
    }

    void Shake()
    {
        originPosition = transform.position;
        originRotation = transform.rotation;
        temp_shake_intensity = shake_intensity;

    }
}
1 Like

Privacy & Terms