Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to assign sprite width by screen width?

Discussion in '2D' started by fehmi, Mar 4, 2015.

  1. fehmi

    fehmi

    Joined:
    Feb 6, 2015
    Posts:
    8
    I am trying to scale my sprite's width via screen width in my 2D experiment. I want my sprite to fill screen horizontaly. Here is the code i tried. It causes an unexpected margin both left and right you can see. How can i done that correctly?

    Thank you

    Code (JavaScript):
    1.  
    2. function Start () {
    3. //set enemy width by screen width
    4. var verticalSize = Camera.main.orthographicSize;
    5. var horizontalSize = verticalSize * Screen.width / Screen.height;
    6. transform.localScale.x = horizontalSize/2;
    7. }
    8.  
    screenWidth.png
     
  2. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    899
    fehmi likes this.
  3. fehmi

    fehmi

    Joined:
    Feb 6, 2015
    Posts:
    8
  4. fehmi

    fehmi

    Joined:
    Feb 6, 2015
    Posts:
    8
  5. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    899
    This scales in both directions (note, however, that it doesn't retain the proportions):

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Scaler : MonoBehaviour
    5. {
    6.     void Start()
    7.     {
    8.         Vector2 cameraSize =
    9.             Camera.main.ViewportToWorldPoint(Vector3.one) -
    10.             Camera.main.ViewportToWorldPoint(Vector3.zero);
    11.  
    12.         float sizeX= Mathf.Abs(cameraSize.x) / (renderer.bounds.size.x / transform.localScale.x);
    13.         float sizeY= Mathf.Abs(cameraSize.y) / (renderer.bounds.size.y / transform.localScale.y);
    14.  
    15.         transform.localScale = new Vector3(sizeX, sizeY, 1);
    16.     }
    17. }
     
  6. fehmi

    fehmi

    Joined:
    Feb 6, 2015
    Posts:
    8
    Sorry, it works, my bad.
     
    Last edited: Mar 5, 2015