91 lines
2.4 KiB
C#
91 lines
2.4 KiB
C#
namespace ArionDigital
|
|
{
|
|
using UnityEngine;
|
|
|
|
public class CrashCrate : MonoBehaviour
|
|
{
|
|
[Header("Whole Crate")]
|
|
public MeshRenderer wholeCrate;
|
|
public BoxCollider boxCollider;
|
|
|
|
[Header("Fractured Crate")]
|
|
public GameObject fracturedCrate; // parent object with all fractured pieces (initially disabled)
|
|
public GameObject[] crackPiecesPerTap; // individual pieces to show before full break
|
|
|
|
[Header("Audio")]
|
|
public AudioSource audioSource;
|
|
public AudioClip crackSound;
|
|
public AudioClip crashSound;
|
|
|
|
private int hitCount = 0;
|
|
private const int maxHits = 5;
|
|
|
|
void Start()
|
|
{
|
|
// Make sure fractured crate and crack pieces are hidden at start
|
|
fracturedCrate.SetActive(false);
|
|
foreach (var piece in crackPiecesPerTap)
|
|
{
|
|
piece.SetActive(false);
|
|
}
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
if (Input.GetMouseButtonDown(0)) // Tap or click
|
|
{
|
|
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
|
|
if (Physics.Raycast(ray, out RaycastHit hit))
|
|
{
|
|
if (hit.collider.gameObject == gameObject)
|
|
{
|
|
RegisterHit();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private void RegisterHit()
|
|
{
|
|
hitCount++;
|
|
|
|
if (hitCount < maxHits)
|
|
{
|
|
// Enable crack pieces one-by-one
|
|
if (hitCount - 1 < crackPiecesPerTap.Length)
|
|
{
|
|
crackPiecesPerTap[hitCount - 1].SetActive(true);
|
|
}
|
|
|
|
if (crackSound && audioSource)
|
|
audioSource.PlayOneShot(crackSound);
|
|
}
|
|
else
|
|
{
|
|
BreakCrate();
|
|
}
|
|
}
|
|
|
|
private void BreakCrate()
|
|
{
|
|
wholeCrate.enabled = false;
|
|
boxCollider.enabled = false;
|
|
fracturedCrate.SetActive(true);
|
|
|
|
if (crashSound && audioSource)
|
|
audioSource.PlayOneShot(crashSound);
|
|
|
|
Invoke(nameof(Destroyer),1);
|
|
}
|
|
void Destroyer()
|
|
{
|
|
gameObject.SetActive(false);
|
|
}
|
|
[ContextMenu("Test")]
|
|
public void Test()
|
|
{
|
|
RegisterHit();
|
|
}
|
|
}
|
|
}
|