Walk on square 2D

Hi. I already search, but nothing can help me. I have difficult to implement a walk on a square, i need to rotate object when it changes surface, and then change gravity


Can anyone help me? Thanks in advance

Did you try using a CircleCollider for the character, and getting the collision normal in OnCollisionStay2D ?

You should be able to use the normal to define gravity, and depending of your script, your walkable plane.

EDIT : Or you could still have a BoxCollider on your character, but you’ll need to use CircleColliders on each corners to have a smooth transition.

EDIT2: Following your comment, you can determine your end position for linecasting with your orientation. And you can change your orientation with the OnCollisionStay2D, if you use a non-kinematic rigidbody on the player, and a kinematic rigidbody with the floor.

Please note that I do not have tested the following code.

Your line casting would look like :

        Physics2D.Linecast(start.position, -start.transform.up * linecastDistance, 1 << LayerMask.NameToLayer("floor"));

and in OnCollisionStay2D :

    public void OnCollisionStay2D(Collision2D collision)
        Quaternion diff = Quaternion.FromToRotation(-start.up, -collision.contacts[0].normal);

        Physics2D.gravity = -collision.contacts[0].normal;

        transform.rotation *= diff;

Of course, I’m assuming you are using the physics gravity, with both GameObjects (Floor and character) having a kinematic/non-kinematic rigidbody.

I also assume that start in parented to the character’s gameobject.