AddForce 2D dependent on Distance from Explosion

Hello!

Im trying to dev my own Explosion Script and it already works to 90%.
On Click the Object “Explosion” will be spawned at mousePosition which has a Trigger on it and the Tag “ERadius1”.

My problem is the “FORCE” in my AddForce Line. It changes dependent on the Distance of the Click to the Object. And this works! So if I click far away from my Object and the Collider still hits it the float FORCE is lower than if i click directly in the Object. Thats exactly how i want it so that my ExplosionForce gets less effective if the Object is far away. But now I figured out it doesnt matter how far away I click. It seems like the Object is only affected by the Integer str1 which is 600. It makes no sense. I can see that FORCE is much higher but the Object behaves like its not.

Anyone has an Idea?

Ty!

The Object i want to blow away has the following Script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectManager : MonoBehaviour {

    Vector2 ContactP;
    public Vector2 ExploDir;
    Vector2 ExploOrigin;
    public float VDistance;
    public int str1;
    float time;
    public float FORCE;

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.transform.tag == "ERadius1")
        {
            Debug.Log("E1");
            ContactP = collision.transform.position;
            ExploOrigin = collision.transform.position;
            VDistance = Vector2.Distance(ExploOrigin, new Vector2(transform.position.x, transform.position.y));
            ExploDir = new Vector2(transform.position.x, transform.position.y) - ContactP;
            FORCE = (str1 / VDistance);
            Debug.Log(FORCE);
            GetComponent<Rigidbody2D>().AddForce(ExploDir * FORCE);
            GetComponent<Rigidbody2D>().AddTorque(Random.Range(-90, 90));
        }
    }
}

ExploDir is already scaled to the distance between the object and the explosion. But this scaling is the opposite of what you’re trying to apply with FORCE. (ExploDir has increased scale with distance, while FORCE has decreased scale with distance)

Trying using:

ExploDir = (transform.position - ContactP).normalized;
1 Like

Yes! Thank you. That was the problem and your code works fine.

kind regards