How can I make a gravity field similar to a planetary body?

Hey guys, I’m trying to make a moving spherical 2D object that can pull objects in if they get caught in it’s gravity field but in a way that if they’re not already moving directly to it, and they come in on an angle, they will kind of veer off while being pulled in slightly and gain some speed.

I have tried the following script on my objects (the ones that will be getting manipulated by this gravity field), but I’d rather have a script on the gravity object itself to pull in the other objects if their Tag or Layer is what it’s looking for:

        if (insideGravity)
        {
            Vector3 gravityField = planet.transform.position - transform.position;
            float index = (radius - gravityField.magnitude) / radius;
            rb.AddForce(gravityAmount * gravityField * index);
        }

That bool is set by OnTriggerEnter2D, but I’m open to any way to get it to detect when it’s entered the radius.

And the issue I’m getting with the code above is that it will enter the trigger, and then go straight towards the planet and lock there, I need it to pick up that momentum and then kind of do a large orbit unless it exits the radius and then it should keep it’s momentum until my drag value slows it back down to it’s normal speed.

Also it should be noted that this is how I’m moving the objects that will be acted upon by this gravity field:

Vector2 movement = new Vector2(xDirection, yDirection).normalized;

        rb.velocity = movement * moveSpeed;

I appreciate any and all help you are able to give me! Thank you!

// http://wiki.unity3d.com/index.php/Gravity
using UnityEngine;
using System.Collections.Generic;

public class Gravity : MonoBehaviour
{
public static float range = 1000;

void FixedUpdate () 
{
	Collider[] cols  = Physics.OverlapSphere(transform.position, range); 
	List<Rigidbody> rbs = new List<Rigidbody>();

	foreach(Collider c in cols)
	{
		Rigidbody rb = c.attachedRigidbody;
		if(rb != null && rb != rigidbody && !rbs.Contains(rb))
		{
			rbs.Add(rb);
			Vector3 offset = transform.position - c.transform.position;
			rb.AddForce( offset / offset.sqrMagnitude * rigidbody.mass);
		}
	}
}

}

I’ll give you some code that I wrote outside of Unity for a project a few years ago - it should give you some insight on how to accomplish this:

/// <summary>
        /// Updates the velocity of all planets based on the force of gravity exerted between planets
        /// </summary>
        private void UpdatePlanetVelocities()
        {
            //foreach loop is not efficient in this case, we need to maintain knowledge about the index of a planet
            for (var i = 0; i < m_planets.Count; i++)
            {
                for (var j = 0; j < m_planets.Count; j++)
                {
                    //don't want to recalculate a reaction we have already visited
                    if (j <= i)
                        continue;

                    var force = ForceBetweenPlanets(m_planets*, m_planets[j]);*

m_planets*.ForceThisFrame += force; //Equal and opposite forces*
m_planets[j].ForceThisFrame -= force; //Equal and opposite forces
}

m_planets.Velocity += (m_planets.ForceThisFrame / (float)m_planets*.Mass);
_}
}*_

///


/// Updates the position of all planets with their current velocity
///

private void UpdatePlanetPositions()
{
foreach (var i in m_planets)
{
i.Position += i.Velocity;
}
}

///


/// Returns the gravitional force between A & B, in the direction of A to B
///

///
///
///
private static Vector2f ForceBetweenPlanets(Planet a, Planet b)
{
var d = Utils.Distance(a.Position, b.Position);
//m_GravConst is just a scaling factor that affects how strong the gravity is
var forceMag = m_GravConst * (a.Mass * b.Mass) / d; //Newton’s Law of Universal Gravitation

var forceVector = b.Position - a.Position;
forceVector /= (float)d; //reduce to unit vector
forceVector *= (float)forceMag; //scale to proper magnitude

return forceVector;
}
You should be able to copy most of this - just use your own list of planets that you determine based on triggers/tags, and let Unity’s physics update the position of objects