first commit
This commit is contained in:
45
Assets/Scripts/Breakable.cs
Normal file
45
Assets/Scripts/Breakable.cs
Normal file
@@ -0,0 +1,45 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
public class Breakable : MonoBehaviour
|
||||
{
|
||||
[SerializeField] private GameObject _debrisRoot;
|
||||
[SerializeField] private float _minFallSpeed = 2f;
|
||||
[SerializeField] private float _explosionForce = 100f;
|
||||
[SerializeField] private float _explosionRadius = 2f;
|
||||
[SerializeField] private float _disappearTime = 3f;
|
||||
|
||||
private Rigidbody _rb;
|
||||
private bool _broken = false;
|
||||
|
||||
void Start()
|
||||
{
|
||||
_rb = GetComponent<Rigidbody>();
|
||||
_debrisRoot.SetActive(false);
|
||||
}
|
||||
|
||||
void OnCollisionEnter(Collision collision)
|
||||
{
|
||||
if (_broken) return;
|
||||
if (_rb.velocity.y < -_minFallSpeed)
|
||||
Break(collision.GetContact(0).point);
|
||||
}
|
||||
|
||||
void Break(Vector3 contactPoint)
|
||||
{
|
||||
_broken = true;
|
||||
_debrisRoot.SetActive(true);
|
||||
_debrisRoot.transform.parent = null;
|
||||
|
||||
Rigidbody[] pieces = _debrisRoot.GetComponentsInChildren<Rigidbody>();
|
||||
foreach (var piece in pieces)
|
||||
{
|
||||
piece.velocity = _rb.velocity;
|
||||
piece.AddExplosionForce(_explosionForce, contactPoint, _explosionRadius);
|
||||
}
|
||||
|
||||
Destroy(_debrisRoot, _disappearTime);
|
||||
Destroy(gameObject);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user