3D Gravity towards one object

I am already aware of unity’s directional gravity from the world properties, and have been experimenting quite a bit with it recently… However, I wanted an object to attract all objects in a specific radius (trigger?) around it. Basically, it is a gun that fires a small GameObject that will pull everything in area towards it… Is it possible?

Thanks in advance!

Assuming all the objects that need to be pulled have rigidbodies (and colliders), you can use Physics.OverlapSphere to detect all the objects within a radius, and then manually apply the force using Rigidbody.AddForce.

public class ObjectPuller {
    public float pullRadius = 2;
    public float pullForce = 1;

    public void FixedUpdate() {
        foreach (Collider collider in Physics.OverlapSphere(transform.position, pullRadius) {
            // calculate direction from target to me
            Vector3 forceDirection = transform.position - collider.transform.position;

            // apply force on target towards me
            collider.rigidbody.AddForce(forceDirection.normalized * pullForce * Time.fixedDeltaTime);
        }
    }
}

Perfectly possible, but not using unity’s simple gravity property, which is designed explicitly for the case of pulling stuff in one, fixed, direction.

Instead, you need to apply a force to all objects you want to attract. You can do this in a number of ways, but one way is to attach a attracted behaviour to each object you want to pull towards. It could look something like this:

class Attracted : MonoBehaviour
{
    public GameObject attractedTo;
    public float strengthOfAttraction = 5.0f;

    void Start {}

    void Update
    {
        Vector3 direction = attractedTo.transform.position - transform.position;
        rigidBody.AddForce(strengthOfAttraction * direction);

    }
}

Making sure, when you attach it to an object, you set the attractedTo to be the object that you want to attract them to.

i did this, but to a different need, i created a planet, but now i need to make the ship remain upwards related to the center of the planet, how to do this withouth change the y orientation of the ship ?