To create an explosionForce method for 2D physics objects, follow these steps:
- Copy the project from the previous recipe, and use this copy for this recipe.
- We can add a method to the Rigidbody2D script class by creating the following C# script class called Rigidbody2DExtension:
using UnityEngine;
public static class Rigidbody2DExtension{
public static void AddExplosionForce(this Rigidbody2D body, float explosionForce, Vector3 explosionPosition, float explosionRadius){
Vector3 forceVector = (body.transform.position - explosionPosition);
float wearoff = 1 - (forceVector.magnitude / explosionRadius);
body.AddForce(forceVector.normalized * explosionForce * wearoff);
}
}
- Create a new empty GameObject named explosion.
- Create a C# script class called ExplodeCircle and add an instance object as a component to the child explosion GameObject:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public...