Last active
May 12, 2022 02:58
-
-
Save nothke/832ab3ff37d3e1ee4dadbc54992dd476 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class Breakable : MonoBehaviour | |
{ | |
public float mass = 50; | |
public float impulseThreshold = 10000; | |
Collider _collider; | |
new Collider collider { get { if (!_collider) _collider = GetComponent<Collider>(); return _collider; } } | |
bool isBroken; | |
private void OnTriggerEnter(Collider col) | |
{ | |
if (isBroken) | |
return; | |
var otherRb = col.attachedRigidbody; | |
if (!otherRb) | |
return; | |
collider.isTrigger = false; | |
// Since I don't have collision point info, I use rigidbody position. Not great, but it works.. | |
Vector3 relDir = (transform.position - otherRb.position).normalized; | |
Debug.DrawRay(transform.position, relDir, Color.red, 4); | |
// We need this to make sure a glancing blow doesn't break it | |
float dot = Vector3.Dot(otherRb.velocity, relDir); | |
float relImpulse = otherRb.mass * otherRb.velocity.magnitude * dot; | |
if (relImpulse > impulseThreshold) | |
Break(); | |
else | |
StartCoroutine(TurnBackIntoTriggerCo()); | |
} | |
void Break() | |
{ | |
var rb = gameObject.AddComponent<Rigidbody>(); | |
rb.interpolation = RigidbodyInterpolation.Interpolate; | |
rb.mass = mass; | |
ElectricSpark.e.Spark(transform.position + Vector3.up * 0.3f); | |
isBroken = true; | |
} | |
IEnumerator TurnBackIntoTriggerCo() | |
{ | |
yield return null; | |
yield return null; | |
yield return null; | |
collider.isTrigger = true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment