Gravity Well

How would you create a gravity well? Such that as an object flies past it, if it’s within distance A, it starts pulling the object in, the closer the object the stronger the pull.

Thinking maybe:

  1. Create vector from moving object to Gravity Well
  2. Calc Distance from Object to Gravity Well
  3. If Distance>A apply force on 2dRigidBody in direction of Vector found from Step #1

There’s gotta be a script for this already, I hate wasting time reinventing the wheel…

Thanks,

Vanz

public class Mover : MonoBehaviour
{
    private Vector3 velocity;

    public Attractor[] attractors;

    private void Update()
    {
        foreach(Attractor attractor in attractors)
            velocity += attractor.GetLocalEffect(transform.position);
        
        transform.position += (velocity * Time.deltaTime);
    }
}

public class Attractor : MonoBehaviour
{
    public float range;
    public float mass; // not really a mass, but whatever

    public Vector3 GetLocalEffect(Vector3 position)
    {
        Vector3 delta = position - transform.position;
        if (delta.sqrMagnitude > range * range)
            return Vector3.zero;

        float percentage = (range  -  delta.magnitude) / range;

        return -delta.normalized * percentage * percentage * mass;
    }
}

Wrote that in 2 mins just as an example of what could be done.

EDIT; Just test it for fun, and it works fine. I got a satellite in orbit of a planet.

1 Like

you da man… will give it a spin, thanks…

http://youtu.be/JC3NrzzaJR4

Messing around. A good example that complex system are fun to watch.