AddExplosionForce 2d workaround not working
I'm attempting to create a basic explosion in Unity 2d engine. Unfortunately the unity function addExplosionForce doesn't natively work with 2d rigidbodies, but I was able to find the following workaround on another StackOverflow site, with multiple people stating that it works. However, it's not working for me and I'm not sure what I'm doing wrong. Assistance is appreciated, as I need this urgently for a project.
Update: It seems that it does work, sort of. When the object is extremely close to the origin of the explosion, so close it's overlapping, then the force is applied with incredible strength. But any further away and it becomes completely ineffective.
Here is the workaround; (Link to thread where I found this: https://stackoverflow.com/questions/34250868/unity-addexplosionforce-to-2d)
public static class Rigidbody2DExt
{
public static void AddExplosionForce(this Rigidbody2D rb, float explosionForce, Vector2 explosionPosition, float explosionRadius, float upwardsModifier = 0.0F, ForceMode2D mode = ForceMode2D.Impulse)
{
var explosionDir = rb.position - explosionPosition;
var explosionDistance = explosionDir.magnitude;
// Normalize without computing magnitude again
if (upwardsModifier == 0)
explosionDir /= explosionDistance;
else
{
// From Rigidbody.AddExplosionForce doc:
// If you pass a non-zero value for the upwardsModifier parameter, the direction
// will be modified by subtracting that value from the Y component of the centre point.
explosionDir.y += upwardsModifier;
explosionDir.Normalize();
}
rb.AddForce(Mathf.Lerp(0, explosionForce, (1 - explosionDistance)) * explosionDir, mode);
}
}
And here is the function that calls the AddExplosionForce;
public class Explosion : MonoBehaviour
{
[SerializeField] float affectRadius;
[SerializeField] float explosionPower;
// This function is based off of the Unity Documentation for Rigidbody.AddExplosionForce
public void Detonate()
{
Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, affectRadius);
foreach (Collider2D affectedObject in colliders)
{
Rigidbody2D rb = affectedObject.gameObject.GetComponent<Rigidbody2D>();
Debug.Log(affectedObject);
if (rb != null)
{
rb.AddExplosionForce(explosionPower, transform.position, affectRadius);
Debug.Log("Explosion force of " + explosionPower);
}
}
}
private void OnDrawGizmos()
{
Gizmos.DrawWireSphere(transform.position, affectRadius);
}
}
Once again, any and all suggestions are greatly appreciated, I will be looking for help in other places as well, so I'll let you know if I find anything successful.
Your answer
Follow this Question
Related Questions
How can I isolate just the character to slow down 0 Answers
Ground Check Issue 1 Answer
How do I make a 2D player controlled ball roll when moving? 1 Answer
LookAt in 2d is not working Again :/ 0 Answers