faux gravity in 2d game

Hey guys,

I need a faux gravity to a circle in a 2d game, so the player can walk on it.
Is this possible? Does anyone know a tutorial that can help me out?


There are plenty of introductions around for 3D and 2D implementations of this, and for similar topics.

That said, having made a habit out of doing this in 3D in some form for many of my personal projects, I can give you a few tips on how to get started:

First, gravity: You’ll probably want to give every physics-driven moving object in your scene its own personal gravitation script. In this script, it would make sense to require a Rigidbody2D, since the whole point is to replace it. In this script, turn off gravity for the object (in the case of 2D, set gravityScale to 0), define a Transform (or Vector2) to attract the object towards, then in FixedUpdate(), apply a gravitational force towards the position of (target.position - thisObject.position).normalized * gravitationalForce where “gravitationalForce” would be given a default value of 9.81 (or -9.81, depending on implementation).

By applying that force on each object towards their defined gravitational center point, you can have everything pulled towards anything else you want. Further developments on the concept usually begin to involve Raycasts and surface normals when you begin to involve irregular shapes, but that’s another topic entirely.

Second, rotation: The 2D approach is much, much, much, much, much simpler than the 3D approach to handling rotation and camera control. I’m afraid I can’t offer any specific details, as I’m not confident in my knowledge of 2D Unity axes, but I can tell you that your rotation will often, most likely be perpendicular to the gravitational pull. That means ensuring that your character’s forward vector is equal to either (-y, x) or (y, -x), depending on whether you’re facing left or right.

Hopefully this will be able to at least get you started on the right track. Good luck!

Thank you so much! I will give it a try! :slight_smile:


what about jumping? any idea about how to prevent the player from flying away?

this is the code i use for jumping

   void Jump(){
    Vector2 vertical = new Vector2(rb.velocity.x, JumpSpeed).normalized;
    rb.velocity = rb.transform.position + rb.transform.TransformDirection((vertical) * MoveSpeed * Time.deltaTime);
    rb.velocity = rb.transform.position + rb.transform.TransformDirection((-vertical) * MoveSpeed * Time.deltaTime);


this the code i use for moving, it may interfer one in another

    void Run(int directionOnX)
    Vector2 horizontal = new Vector2(directionOnX, rb.velocity.y).normalized;
    rb.MovePosition(rb.transform.position + rb.transform.TransformDirection((horizontal) * MoveSpeed * Time.deltaTime));