Search code examples
unity-game-enginegame-physicsphysicsgravity

Why a big moving attractor object gives a slingshot to other object with using gravity formula rather than holding it?


I have a big spherical Gameobject which moves forward in 3D with constant velocity. I have other spherical objects that other big object needs to attract to itself. I am using Newton's law of universal gravitation formula to attract other objects, but as expected, other objects are doing a slingshot movement much like the space shuttles doing when needed with other planets' orbits to accelerate.

I actually want a magnetic effect that without taking the masses into account, all other objects will be catched by the big object. How can I do that? Do I need a different formula? Or do I need to change the movement behavior of the objects altogether?


Solution

  • If I got it right you expect to have something like this: https://www.youtube.com/watch?v=33EpYi3uTnQ

    • You can do a spherical raycast or have an sphere collider as trigger to detected the objects that are inside of your magnetic field.
    • Once you know those objects you can calculate the distance from each of them to the magnetic ball.
    • You can make an inverse interpolation to know how much strength/"magnetism" is getting into that object.
    • Then you can apply some force on the attracted object towards the magnetic ball's center.

    Something like this algorithm:

    var objectsInsideField = ListOfObjects;
    foreach (o in objectsInsideField) {
        var distance = (o.position - center.position).magnitude;
        var strength = distance / fieldRadius; // fieldRadius == spherical radius
        o.AddForce(dir: o.position - center.position, strength: strength)
    }
    

    Of course, you need to do some adjustments and probably add some multipliers to make the force to be meaning.

    The final result should be: for each sequential frame, if the object is inside the magnetic field it moves towards the center a bit. The next frame it should be even close to the center so the strength is even bigger.. and so and so.