2
\$\begingroup\$

My background and gameobjects are 2d sprites not UI images ,I want to know how to make my background scale with screen size and positions of 2d sprits on it don't change after building game (webGl) like scale canvas with screen size and anchor points in UI elements .

Before building the game enter image description here

After building enter image description here

\$\endgroup\$
  • \$\begingroup\$ It looks like your content has scaled perfectly to match the height of your display area. Would you like it to scale to match the width instead? Note that this will mean you show more area above and below the currentlt displayed content, which depending on your setup might reveal gaps or require letterboxing. \$\endgroup\$ – DMGregory Jan 21 at 12:12
  • \$\begingroup\$ I want to make it to match the width like it match the height of my display area. and don't display the blue area of the camera \$\endgroup\$ – Sh.Adel Jan 21 at 12:29
2
\$\begingroup\$

You can adjust the camera's height so it scales with the width of the screen like so:

(Place this script on your Camera object)

[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
public class MatchWidth : MonoBehaviour {

    // Set this to the in-world distance between the left & right edges of your scene.
    public float sceneWidth = 10;

    Camera _camera;
    void Start() {
        _camera = GetComponent<Camera>();
    }

    // Adjust the camera's height so the desired scene width fits in view
    // even if the screen/window size changes dynamically.
    void Update() {
        float unitsPerPixel = sceneWidth / Screen.width;

        float desiredHalfHeight = 0.5f * unitsPerPixel * Screen.height;

        camera.orthographicSize = desiredHalfHeight;
    }
}

If you're using a perspective camera, then instead you'd use...

public float horizontalFoV = 90.0f;

// ...

void Update() {
   float halfWidth = Mathf.Tan(0.5f * horizontalFoV * Mathf.Deg2Rad);

   float halfHeight = halfWidth * Screen.height / Screen.width;

   float verticalFoV = 2.0f * Mathf.Atan(halfHeight) * Mathf.Rad2Deg;

   camera.fieldOfView = verticalFoV;
}

If you want to shrink your viewport to add letterboxes instead of showing additional height above/below, you can use the technique described in this answer.

\$\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.