119 lines
3.3 KiB
C#
119 lines
3.3 KiB
C#
namespace ArionDigital
|
|
{
|
|
using UnityEngine;
|
|
|
|
public class CrashCrate : MonoBehaviour
|
|
{
|
|
[Header("Fractured Crate")]
|
|
public GameObject[] crackPiecesPerTap;
|
|
|
|
[Header("Audio")]
|
|
public AudioSource audioSource;
|
|
public AudioClip crackSound;
|
|
public AudioClip crashSound;
|
|
|
|
public Animator dogAnimator;
|
|
|
|
private int hitCount = 0;
|
|
private const int maxHits = 5;
|
|
|
|
void Start()
|
|
{
|
|
foreach (var piece in crackPiecesPerTap)
|
|
{
|
|
if (piece != null)
|
|
{
|
|
piece.SetActive(true); // ✅ keep visible
|
|
var rb = piece.GetComponent<Rigidbody>();
|
|
if (rb) rb.isKinematic = true; // ✅ freeze physics
|
|
}
|
|
}
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
if (Input.GetMouseButtonDown(0))
|
|
{
|
|
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
|
|
if (Physics.Raycast(ray, out RaycastHit hit))
|
|
{
|
|
GameObject touchedObject = hit.collider.gameObject;
|
|
|
|
// Check if the tapped object is in our list
|
|
for (int i = 0; i < crackPiecesPerTap.Length; i++)
|
|
{
|
|
if (crackPiecesPerTap[i] == touchedObject)
|
|
{
|
|
RegisterHit(i);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private void RegisterHit(int index)
|
|
{
|
|
hitCount++;
|
|
|
|
if (hitCount < maxHits)
|
|
{
|
|
var piece = crackPiecesPerTap[index];
|
|
|
|
var rb = piece.GetComponent<Rigidbody>();
|
|
if (rb && rb.isKinematic)
|
|
{
|
|
rb.isKinematic = false;
|
|
Vector3 explosionOrigin = transform.position + Random.insideUnitSphere * 0.5f;
|
|
explosionOrigin.y = transform.position.y - 0.5f; // keep the force coming from slightly below
|
|
|
|
rb.AddExplosionForce(10f, explosionOrigin, 2f, 0.5f, ForceMode.Impulse);
|
|
|
|
}
|
|
|
|
if (crackSound && audioSource)
|
|
audioSource.PlayOneShot(crackSound);
|
|
}
|
|
else
|
|
{
|
|
BreakCrate();
|
|
}
|
|
}
|
|
|
|
private void BreakCrate()
|
|
{
|
|
foreach (var piece in crackPiecesPerTap)
|
|
{
|
|
if (piece != null)
|
|
{
|
|
var rb = piece.GetComponent<Rigidbody>();
|
|
if (rb && rb.isKinematic)
|
|
{
|
|
rb.isKinematic = false;
|
|
rb.AddExplosionForce(300f, transform.position, 2f);
|
|
}
|
|
}
|
|
}
|
|
|
|
if (crashSound && audioSource)
|
|
audioSource.PlayOneShot(crashSound);
|
|
|
|
if (dogAnimator)
|
|
dogAnimator.SetInteger("state", 1);
|
|
|
|
Invoke(nameof(Destroyer), 1f);
|
|
}
|
|
|
|
private void Destroyer()
|
|
{
|
|
gameObject.SetActive(false);
|
|
}
|
|
|
|
[ContextMenu("Test Hit Index 0")]
|
|
public void Test()
|
|
{
|
|
RegisterHit(0);
|
|
}
|
|
}
|
|
}
|