Unity/오늘 알아낸 것

해상도에 맞게 트렌스폼 포지션과 스케일 맞추기

Potatopotatopotato 2023. 8. 12. 21:21

어제까지 진행한 프로젝트에 가변 해상도를 넣고 싶었는데 고정 해상도로 가자고해서 못넣었던 기능을 간단하게 만들어봤다

트랜스폼이 해상도에 맞게 변경되어야하는 게임들 카드 게임, 클릭 앤 포인트 어드벤쳐등에 쓸수있겠다

(굳이 UGUI로 때우겠다면 말리진 않음)

 

using UnityEngine;

public class ObjectTransformTuner : MonoBehaviour
{
    Vector2 targetResolution = new Vector2(1920, 1080);
    Vector3 targetPosition;
    Vector3 targetScale;

    private void Start()
    {
        targetPosition = transform.position;
        targetScale = transform.localScale;
    }

    [ContextMenu("UpdateScale")]
    void UpdateTransform()
    {
        Vector2 currentResolution = 
            new Vector2((float)Screen.width / targetResolution.x, (float)Screen.height / targetResolution.y);

        Vector3 calculatedPosition = new Vector3(
            targetPosition.x * currentResolution.x, 
            targetPosition.y * currentResolution.y, 
            targetPosition.z);
        Vector3 calculatedScale    = targetScale * Mathf.Min(currentResolution.x, currentResolution.y);

        gameObject.transform.position   = calculatedPosition;
        gameObject.transform.localScale = calculatedScale;
    }
}

 

상속해서 쓰던지 아니면 자식 클래스에 박아버리던지 하면 될거같다

그리고 에디터상에선 제대로 작동이 되지않을수있다

에디터는 Screen.width, Screen.height가 게임 뷰의 크기와 해상도 설정에 따라서 달라지기 때문이다

하지만 실제로 빌드해서 사용하면 제대로된 값이 나와서 문제 없이 작동 될것이니 걱정하지 않아도 된다

(영상에선 고정 값을 하드 코딩하여 촬영했다 빌드하기 귀찮았음)

 

실제로 게임에 적용됬을때를 확인 하고 싶은데 다음 프로젝트땐 여러 기기로 테스트 할 수 있었으면 좋겠다