0
\$\begingroup\$

I've been trying to enforce a 4:3 aspect ratio in my Unity game, in order to give a nostalgia feeling to it. But whenever I add this script to my camera and compile my game, it blurs slightly. I am using a 4:3 aspect ratio in the game view and have Fullscreen Window chosen in my Window Option and in Supported Resolutions I have only 4:3 ticked. Also, I am used Pixel Perfect Camera with Pixel Snapping enabled.

Here's what my game looks like without the CameraCrop script added:

enter image description here

And here is what it looks like when the script is added:

enter image description here

Here's the script I add to my camera:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

// Requires that the camera component is on the GameObject
[RequireComponent(typeof(Camera))]
public class CameraCrop : MonoBehaviour
{

    // Sets the aspect ratio to whatever you want
    public Vector2 targetAspect = new Vector2(4, 3);
    Camera _camera;

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

    // Call this method if your window size or target aspect change.
    public void UpdateCrop()
    {
        // Determine ratios of screen/window & target, respectively.
        float screenRatio = Screen.width / (float)Screen.height;
        float targetRatio = targetAspect.x / targetAspect.y;

        if (Mathf.Approximately(screenRatio, targetRatio))
        {
            // Screen or window is the target aspect ratio: use the whole area.
            _camera.rect = new Rect(0, 0, 1, 1);
        }
        else if (screenRatio > targetRatio)
        {
            // Screen or window is wider than the target: pillarbox.
            float normalizedWidth = targetRatio / screenRatio;
            float barThickness = (1f - normalizedWidth) / 2f;
            _camera.rect = new Rect(barThickness, 0, normalizedWidth, 1);
        }
        else
        {
            // Screen or window is narrower than the target: letterbox.
            float normalizedHeight = screenRatio / targetRatio;
            float barThickness = (1f - normalizedHeight) / 2f;
            _camera.rect = new Rect(0, barThickness, 1, normalizedHeight);
        }
    }
}

I am using Unity 2019.4.17f LTS and using Windows 10.

\$\endgroup\$
0

Your Answer

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

Browse other questions tagged or ask your own question.