출처 [Unity] 마우스로 카메라 줌 인, 줌 아웃, 회전 시키기 — 코덕 개발자 노트 (tistory.com)

 

[Unity] 마우스로 카메라 줌 인, 줌 아웃, 회전 시키기

이전 포스트 2019/06/25 - [Development/Game] - [Unity] 마우스 클릭한 지점으로 캐릭터 이동시키기 [Unity] 마우스 클릭한 지점으로 캐릭터 이동시키기 대부분 유니티 캐릭터 이동 예제를 보면 키보드의 입

cjwoov.tistory.com

 

MouseControl.cs라는 스크립트를 만들어서 Main Camera 오브젝트에 추가

- Update 함수에서 Zoom함수와 Rotate함수 호출

- 줌

   -> 마우스 휠 시, MainCamera의 fieldOfView 속성값 갱신

   -> 최소/최대 제한시, fieldOfView속성값을 if문으로 제어

- 회전

   -> 마우스 오른쪽 버튼 누른 상태로 이동 시 회전

 

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

public class CameraCtrl : MonoBehaviour
{
    public float rotateSpeed = 10.0f;
    public float zoomSpeed = 10.0f;
    private Camera mainCamera;

    // Start is called before the first frame update
    void Start()
    {
        mainCamera = GetComponent<Camera>();
    }

    // Update is called once per frame
    void Update()
    {
        Zoom();
        Rotate();
    }

    private void Zoom()
    {
        float distance = Input.GetAxis("Mouse ScrollWheel") * -1 * zoomSpeed;
        if(distance != 0)
        {
            mainCamera.fieldOfView += distance;
        }
    }

    private void Rotate()
    {
        if (Input.GetMouseButton(1))
        {
            Vector3 angles = transform.rotation.eulerAngles;           // 현재 카메라 각도 -> Vector3
            angles.y += Input.GetAxis("Mouse X") * rotateSpeed;        // 마우스 X * 속도
            angles.x += -1 * Input.GetAxis("Mouse Y") * rotateSpeed;   // 마우스 Y * 속도
            Quaternion q = Quaternion.Euler(angles);                   // Quaternion으로 변환 (자연스러운 회전위함)
            q.z = 0;
            transform.rotation = Quaternion.Slerp(transform.rotation, q, 2f);
        }
    }
}