Unity3d: how to apply a vortex like force to objects?

Viewed 676

I would like to simulate a vortex like force to a "bunch" of objects in my scene.

How can I do in Unity ?

Thanks

2 Answers

Circular motion:

 float angle =0;
 float speed=(2*Mathf.PI)/5 //2*PI in degress is 360, so you get 5 seconds to complete a circle
 float radius=5;
 void Update()
 {
     angle += speed*Time.deltaTime; //if you want to switch direction, use -= instead of +=
     x = Mathf.Cos(angle)*radius;
     y = Mathf.Sin(angle)*radius;
 }

where the center of your circle is the center of your vortex.

Of course:

  • If you want multiple objects with diferent distance from vortex's
    center you have to play with your radius variable (i would add a
    Random.Range(minDistance, maxDistance))

  • If you want diferent speeds you can randomize/change the speed.

  • Randomize/change your x/y if you don't want a perfect circle

Hope i was clear enought.

If you are using the physics system, there's two parts to this. Applying the vortex force, and getting the nice swirling effect. To apply the vortex force you can just loop over the rigidbodies and apply the force. To make the swirl look like a proper vortex swirl, you need to start the objects off with a tangential velocity that you can figure out using the vector cross product.

public float VortexStrength = 1000f;

public float SwirlStrength = 5f;

void Start () {
    foreach(GameObject g in RigidBodies){
        //to get them nice and swirly, use the perpendicular to the direction to the vortex
        Vector3 direction = Vortex.transform.position - g.transform.position;
        var tangent = Vector3.Cross(direction, Vector3.up).normalized * SwirlStrength;
        g.GetComponent<Rigidbody>().velocity = tangent;
    }
}

void Update(){
    //apply the vortex force
    foreach(GameObject g in RigidBodies){
        //force them toward the center
        Vector3 direction = Vortex.transform.position - g.transform.position;
        g.GetComponent<Rigidbody>().AddForce(direction.normalized * Time.deltaTime * VortexStrength);
    }
}
Related