Skip to content

Instantly share code, notes, and snippets.

@farukcan
Created January 17, 2022 21:06
Show Gist options
  • Save farukcan/861840a1872fe3a4864cb9c528087e5f to your computer and use it in GitHub Desktop.
Save farukcan/861840a1872fe3a4864cb9c528087e5f to your computer and use it in GitHub Desktop.
Unity Physical Explosion Script
// Author : github.com/farukcan
// Usage :
// explosion.Explode();
// or enable explodeOnStart before instantiation
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Explosion : MonoBehaviour
{
public bool explodeOnStart = false;
public float radius = 1f;
public float power = 1f;
public float upwardForce = 1f;
public bool haptic = false;
#if UNITY_EDITOR
private void OnDrawGizmos()
{
Gizmos.DrawWireSphere(transform.position, radius);
}
#endif
private void Start()
{
if (explodeOnStart)
{
Explode();
}
}
public void Explode()
{
Debug.Log(name + " Explosion");
Vector3 explosionPos = transform.position;
foreach (var col in Physics.OverlapSphere(transform.position, radius))
{
Rigidbody rb = col.GetComponent<Rigidbody>();
if (rb != null)
rb.AddExplosionForce(power, explosionPos, radius, upwardForce);
}
if (haptic)
{
// Requires Haptic : https://github.com/farukcan/unity-utilities
Haptic.MediumTaptic();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment