내일배움캠프 TIL

내일배움캠프 24일차 TIL "화면 내 좌표 구하기"

Jooglorystar 2024. 10. 17. 21:06

 

 

특정 오브젝트가 마우스를 따라 다니게 하고 싶다면 다음과 같이 코드를 작성할 수 있다.

 

 

private void SetAimPoint()
{
    Vector2 mousePos = Input.mousePosition;
    Vector2 newPos = _camera.ScreenToWorldPoint(mousePos);
    transform.position = new Vector2(newPos.x, newPos.y);
}

 

 

그러나 이 방법에는 한가지 거슬리는 점이 있을 수 있는데, 해당 오브젝트가 화면 밖으로도 나갈 수 있다는 점이다.

게임을 전체화면으로 진행할 때는 별 문제가 없을 수도 있으나, 특정 상황에서는 곤란한 상황이 발생할 수 있다.

 

 

이를 방지하기 위해 다음과 같이 코드를 작성할 수 있다.

 

private Camera _camera;

private void Awake()
{
    _camera = Camera.main;
}

private void SetAimPoint(Vector2 vector)
{
    Vector2 bottomLeft = _camera.ViewportToWorldPoint(new Vector3(0, 0, _camera.nearClipPlane));
    Vector2 topRight = _camera.ViewportToWorldPoint(new Vector3(1, 1, _camera.nearClipPlane));

    float pointX = Mathf.Clamp(vector.x, bottomLeft.x, topRight.x);
    float pointY = Mathf.Clamp(vector.y, bottomLeft.y, topRight.y);

    transform.position = new Vector2(pointX, pointY);
}

 

ViewportToWorldPoint를 하면 해당 카메라로 보이는 곳에서의 월드 좌표를 구할 수 있다.

x값과 y값이 0이면, 화면상 좌측 하단의 월드 좌표를 알려주고, 1이면 우측 상단 월드 좌표를 알려준다.

_camera.nearClipPlane은 카메라의 거리를 계산해서 정확한 월드 좌표를 알려준다고 보면 된다.

이를 통해 화면상의 최대값과 최소 값을 알 수 있다.

 

Mathf.Clamp(value, min, max)는 해당 값의 최대 값과 최소 값을 정할 수 있는 메서드이다.


해당 코드는 bottomLeft와 topRight에 월드 좌표의 최대값과 최소값을 구했고,

Mathf.Clamp에 bottomLeft와 topRight의 x값과 y값을 최대 최소 값에 적절하게 배치하여 pointX값과 pointY값을 월드 좌표 내로 한정지었다.