Unity/Unity

[Unity 2D]마우스 휠로 ZoomIn/ZoomOut 사용하기 - Hide

zz0zz9 2024. 11. 4. 00:39
반응형

 

[SerializeField] private float zoomSpeed = 10f;
[SerializeField] private float minZoom = -20f;
[SerializeField] private float maxZoom = 50f;
private Camera camera;

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

private void Update()
{
    float scrollInput = Input.GetAxis("Mouse ScrollWheel");
    Debug.Log("Scroll Input:" + scrollInput); //에디터 확인용
    
    camera.orthographicSize -= scrollInput * zoomSpeed;
    camera.orthographicSize = Mathf.Clamp(camera.orthographicSize, minZoom, maxZoom);
}

Mathf.Clamp(value, 최소값, 최대값) : value의 크기를 min과 max 사이로 조정한다.

 

 

 

여기서 좀 더 부드럽게 ZoomIn/ZoomOut 하고 싶다면 선형 보간(Lerp)을 사용한다.

[SerializeField] private float zoomSpeed = 10f;
[SerializeField] private float minZoom = -20f;
[SerializeField] private float maxZoom = 50f;
[SerializeField] private float smooth = 5f;

private Camera camera;
private float target;

private void Start()
{
    camera = GetComponent<Camera>();
    target = camera.orthographicSize;
}
private void Update()
{
    float scrollInput = Input.GetAxis("Mouse ScrollWheel");
    Debug.Log("Scroll Input:" + scrollInput);

    target -= scrollInput * zoomSpeed;
    target = Mathf.Clamp(target, minZoom, maxZoom);
    camera.orthographicSize=Mathf.Lerp(camera.orthographicSize, target, Time.deltaTime*smooth);
}

 

+ 마우스 좌클릭으로 MainCamera Position 바꾸는 법

[SerializeField] private float zoomSpeed = 10f;
[SerializeField] private float minZoom = -20f;
[SerializeField] private float maxZoom = 50f;
[SerializeField] private float smooth = 5f;
[SerializeField] private float dragSpeed = 1f;

private Camera camera;
private float target;
private Vector3 dragOrigin;

private void Start()
{
    camera = GetComponent<Camera>();
    target = camera.orthographicSize;
}
private void Update()
{
    float scrollInput = Input.GetAxis("Mouse ScrollWheel");
    Debug.Log("Scroll Input:" + scrollInput);

    target-=scrollInput * zoomSpeed;
    target=Mathf.Clamp(target,minZoom,maxZoom);
    camera.orthographicSize=Mathf.Lerp(camera.orthographicSize, target, Time.deltaTime*smooth);

    if(Input.GetMouseButtonDown(1)) dragOrigin= Camera.main.ScreenToWorldPoint(Input.mousePosition);
    if(Input.GetMouseButton(1))
    {
        Vector3 currentMousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Vector3 difference = dragOrigin - currentMousePos;
        Camera.main.transform.position += difference * dragSpeed;
        dragOrigin = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    }
}

GetMouseButtonDown : 한 번 눌렀을 때

GetMouseButton : 누르는 동안


유니티 하다 어려우면 코테로 회피

코테 하다 어려우면 유니티로 회피

반응형