개발 라이브러리 & 툴/유니티
Unity 2D 카메라 화면 크기 및 좌표 범위 얻기
하늘흐늘
2021. 11. 24. 19:09
반응형
Unity로 2D 게임을 만들다보면 카메라가 표시하는 화면 좌표에 대한 정보를 얻어야 할 때가 있습니다. 그럴 때 카메라가 표시하는 화면의 왼쪽(Left), 오른쪽(Right), 위(Top), 아래(Bottom), 전체 길이(Width), 전체 높이(Height) 등의 정보가 필요합니다.
아래 소스는 camera_ 변수에 화면을 표시하는 카메라를 설정하면 화면의 왼쪽(Left) x좌표, 오른쪽(Right) x좌표, 위(Top) y좌표, 아래(Bottom) y좌표 및 전체 길이(Width), 전체 높이(Height) 등을 얻는 간단한 소스 예제입니다.
예제 소스에서는 마우스 오른쪽 버튼을 누르면 해당 정보가 디버그로 표시하게 해놓았습니다.
참고로 해당 소스는 간단히 만든 관계로 camera_에 대한 null처리는 하지 않았습니다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraBound : MonoBehaviour
{
public Camera camera_ = null;
private float size_y_;
private float size_x_;
public float Bottom
{
get
{
return size_y_ * -1 + camera_.gameObject.transform.position.y;
}
}
public float Top
{
get
{
return size_y_ + camera_.gameObject.transform.position.y;
}
}
public float Left
{
get
{
return size_x_ * -1 + camera_.gameObject.transform.position.x;
}
}
public float Right
{
get
{
return size_x_ + camera_.gameObject.transform.position.x;
}
}
public float Height
{
get
{
return size_y_ * 2;
}
}
public float Width
{
get
{
return size_x_ * 2;
}
}
void Start()
{
size_y_ = camera_.orthographicSize;
size_x_ = camera_.orthographicSize * Screen.width / Screen.height;
}
void Update()
{
if (Input.GetMouseButtonDown(1))
{
string msg =
string.Format("스크린 좌표: ({0}, {1}) ~ ({2}, {3}) : {4} x {5}",
Left, Top, Right, Bottom, Width, Height
);
Debug.Log(msg);
}
}
}
반응형