How do I make a mechanic that allows you to move into the background and foreground?

So I’m making a 2D platformer and want to add a gimmick that might make the game more interesting; that being the ability to move between the background and foreground like in Virtual Boy Wario Land, or more specifically, a cancelled Mario game called Mario Adventure (or Virtual Boy Mario Land), where you cross a bridge to move over to the background. The only problem is that I don’t know how I can accomplish this, and I haven’t been able to find anything on Google, YouTube, or Unity Answers that could help (the closest thing I could find was this: If anyone has an idea on how to do it, just let me know. I’m not exactly the best at coding, but I do understand the gist of it.


It can be done using Unity Collision Matrix…Basically setting up two layers (Foreground and background) and allowing the player to move in between

  1. First Create Two Layers

  2. Set up the collision matrix so Foreground objects don’t collide with Background objects (Edit-> Project Settings → Physics 2d)

  3. Now just change the layer of the player… here is a simple code

    [SerializeField] float speed = 1.0f;
    [SerializeField] Rigidbody2D playerRigidbody2D;
    private void FixedUpdate()
    float x = Input.GetAxis(“Horizontal”);
    playerRigidbody2D.velocity = new Vector2(x * speed, 0f);

     if (Input.GetKey(KeyCode.UpArrow))
         gameObject.layer = LayerMask.NameToLayer("Background");
     else if (Input.GetKey(KeyCode.DownArrow))
         gameObject.layer = LayerMask.NameToLayer("Foreground");


  4. Finally Managing the sorting layer in the sprite Renderer to render everything correctly