I have a title screen with a bunch of objects scattered around, when the player hits the play button I want an explosion to go off in the background flinging all the objects around.
I can theoretically see how to do this by working out each individual objects position relative to the epicentre of the explosion and then adding a force in the opposite direction (scaled due to distance) but I was wondering if Unity have provided an easier way to accomplish this?
My game is 2D if that changes anything.
In Unity, 2D and 3D physics using different physics engines so 2D objects can’t collide with 3D objects but you can create hybrid (2D - 3D) game objects by adding a 3D Collider and Rigidbody to your sprites then you can use Rigidbody.AddExplosionForce method which is only work with 3D Rigidbody component.
So, simply add 3D Box Collider and 3D Rigidbody component to your sprites then you can use Rigidbody.AddExplosionForce to create a satisfying explosion effect.
using UnityEngine;
using System.Collections;
// Applies an explosion force to all nearby rigidbodies
public class ExampleClass : MonoBehaviour
{
public float radius = 5.0F;
public float power = 10.0F;
void Start()
{
Vector3 explosionPos = transform.position;
Collider[] colliders = Physics.OverlapSphere(explosionPos, radius);
foreach (Collider hit in colliders)
{
Rigidbody rb = hit.GetComponent<Rigidbody>();
if (rb != null)
rb.AddExplosionForce(power, explosionPos, radius, 3.0F);
}
}
}
Related Links:
https://docs.unity3d.com/ScriptReference/ForceMode2D.Impulse.html
https://docs.unity3d.com/ScriptReference/Rigidbody.AddExplosionForce.html
https://answers.unity.com/questions/580769/can-rigidbody-2d-collide-with-3d-colliders.html
https://forum.unity.com/threads/need-rigidbody2d-addexplosionforce.212173/