3
\$\begingroup\$

I'm trying to resize my small background sprite to match the screen width of the user's device.

This is what I'm trying

// Use this for initialization
void Start () {
    // Set filterMode
    SpriteRenderer sr = (SpriteRenderer) GetComponent("Renderer");
    sr.sprite.texture.filterMode = FilterMode.Point;

    // Get scaling
    float multiplier = Camera.main.rect.width / sr.sprite.bounds.size.x;

    // Scale
    transform.localScale = localScale * multiplier;
}

It seems there is a problem with the measure I get from the Camera width, I also tried Screen.width but it seems it returns the value in pixels.

\$\endgroup\$
4
\$\begingroup\$

This functions should scale the sprite proportionally so it fits the camera width:

void fitCameraWidth() {
    SpriteRenderer sr = (SpriteRenderer)GetComponent ("Renderer");
    if (sr == null)
        return;

    // Set filterMode
    sr.sprite.texture.filterMode = FilterMode.Point;

    // Get stuff
    double width = sr.sprite.bounds.size.x;
    Debug.Log ("width: " + width);
    double worldScreenHeight = Camera.main.orthographicSize * 2.0;
    double worldScreenWidth = worldScreenHeight / Screen.height * Screen.width;

    // Resize
    transform.localScale = new Vector2 (1, 1) * (float)(worldScreenWidth / width);
}

If what you want to do if resize to fit the camera height (if your game is played in landscape this is probably what you would want):

void fitCameraHeight() {
    SpriteRenderer sr = (SpriteRenderer)GetComponent ("Renderer");
    if (sr == null)
        return;

    // Set filterMode
    sr.sprite.texture.filterMode = FilterMode.Point;

    // Get stuff
    double width = sr.sprite.bounds.size.x;
    double worldScreenHeight = Camera.main.orthographicSize * 2.0;

    // Resize
    transform.localScale = new Vector2 (1, 1) * (float)(worldScreenHeight / height);
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.