Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

2D - Background fit adapt to screen mobile resolution

Discussion in '2D' started by martur94, Sep 20, 2017.

  1. martur94

    martur94

    Joined:
    Dec 22, 2015
    Posts:
    17
    I would like my background to adapt to changes resolutions in mobile devices.

    Can check in images, i need layout only fit the main camera resolution

    image1.png


    image2.png


    What can i do ?
     
  2. MiladZarrin1

    MiladZarrin1

    Joined:
    Jul 7, 2013
    Posts:
    78
    Do you want to change the aspect ratio of the image?
    In other words, you want to have your image completely fill your camera view port, Either in landscape or portrait mode? And you don't mind it'll be deformed?
     
  3. martur94

    martur94

    Joined:
    Dec 22, 2015
    Posts:
    17
    Only in portrait mode...
     
  4. samizzo

    samizzo

    Joined:
    Sep 7, 2011
    Posts:
    487
    You'll have to explain a bit more what result you want. Are you trying to support both landscape and portrait, and have your background look correct in both?

    -sam
     
  5. MiladZarrin1

    MiladZarrin1

    Joined:
    Jul 7, 2013
    Posts:
    78
    I think this code will do what you want:

    Code (CSharp):
    1. float spriteActualWidth = renderer.sprite.bounds.size.x * renderer.transform.localScale.x;
    2. float spriteActualHeight = renderer.sprite.bounds.size.y * renderer.transform.localScale.y;
    3.  
    4. float widthMultiplyer = (Camera.main.orthographicSize * Camera.main.aspect) / spriteActualWidth;
    5. float heightMultiplyer = (Camera.main.orthographicSize) / spriteActualHeight;
    6.  
    7. renderer.transform.localScale = new Vector3(widthMultiplyer * renderer.transform.localScale.x * 2, heightMultiplyer * renderer.transform.localScale.y * 2, renderer.transform.localScale.z);

    Let me know if I am wrong.
     
    Last edited: Sep 28, 2017
    ronald_20010820 likes this.