apply force to objects within an area and other stuff

Bit of a messy example, but it demonstrates a few things in a simple way.

1 - finding the gameobjects that a collider is connected to

2 - finding the rigidbody component of said gameobject

3 - applying a force to rigidbody

4 - optional destroying gameobjects

5 - Oh and the "Physics Overlap Sphere" function. It returns all the colliders within a given spherical volume.

 

public void physicsSphereMake(Vector3 coord, float radius, float multiply)
    {
     //get an array of colliders within an overlap sphere that we provide position and radius for   

        Collider[] hitColliders = Physics.OverlapSphere(coord, radius);   

    //loop through array

        foreach(var hitCollider in hitColliders)
        {

            //find out the game object
            GameObject temp = hitCollider.gameObject;

            //find the rigidbody (more on this in a bit)
            Rigidbody rb_temp = temp.GetComponent<Rigidbody>();

            //get position of the game object
            Vector3 pos_temp = temp.transform.position;

            //do some maths to calculate the force we want to apply, subtract sphere centre from object position to get direction, get the magnitude of the direction then multiply by a ratio to get the actual force.
            Vector3 force_temp_dir = (pos_temp - coord) ;
            float force_mult = radius/force_temp_dir.magnitude;
            Vector3 force_temp = force_temp_dir * force_mult*multiply;


         //here we check that the rigidbody has worked. Unity will return NULL if it doesn't find one.
 

            if (rb_temp !=null)
            {
                Debug.Log("applying force to " + rb_temp);

//apply force here
                rb_temp.AddForce(force_temp, ForceMode.Impulse);
                //Destroy(hitCollider.gameObject, 2.0f);
                //Debug.Log("destroyed " + hitCollider.gameObject);
            }    
        }

    }

 

 

Comments

Popular posts from this blog

setting VFX graph properties using C#

scripting custom render texture creation, assignment, shaders