Home > Back-end >  How to make object pull another in Unity 2D
How to make object pull another in Unity 2D

Time:10-10

So I'm trying to simulate orbital mechanics in Unity 2D. I have a ship and Moon model in scene. I calculated the sphere of influence, and if the distance between the Moon and ship is smaller than sphere of influence, the gravity will effect. Problem is;

I can't get gravity affect working.

I've tried using AddForce method, but since it requires Vector2 elements and I calculate my force as float (I use Newton's law of gravitation formula and I get a float), I don't know how to include my float force in Vector2 force.

force = (GravitationalConstant * ((planetMass * ship.GetComponent<Rigidbody2D>().mass)/Mathf.Pow(Vector3.Distance(ship.transform.position,transform.position),2)))/(realityConstant * forceReducer);
    if (Vector3.Distance(transform.position,ship.transform.position) < SOI/realityConstant){
        ship.GetComponent<Rigidbody2D>().AddForce(new Vector2((float)force,0f));
    }

This code makes Moon pull the ship to itself only from left side. When ship passes Moon, it keeps pushing it to right. Not to itself.

I need a fix, that makes Moon pull the ship to itself everytime, with a specific force. How do i make this happen?

Any idea would be helpful.

Thanks a lot!

CodePudding user response:

Force is applied using a vector. You have the magnitude of your vector but not its direction. You can calculate a direction by subtracting moon position from the ship position:

ship.GetComponent<Rigidbody2D>().AddForce((Moon.transform.position -
 ship.transform.position).normalize * force);
  • Related