Unity

키보드 및 마우스를 통한 카메라 이동, 회전

Dean83 2023. 11. 9. 13:17

카메라 이동을 할 경우, 직접 카메라를 이동하는것도 좋고, CharacterController 를 쓰는것도 좋다.

 

CharacterController 는 inspector에서 추가 하면 된다. 카메라에 추가해 두면 된다. 

 

마우스 우클릭시 카메라의 각도를 변경하고, wsad와 방향키로 이동을 하며, q 와 e 로 위 아래로

 

움직이도록 해 놓았다.  맴버변수와 업데이트 문 예제이다. 

 

	public Transform cameraTransform;
    public CharacterController characterController;
    public float speed = 0.5f;
    public float jumpForce = 0.2f;
    public float sensitivity = 1f;
    private bool isRotating = false;

    // Update is called once per frame
    void Update()
    {
        float translationX = Input.GetAxis("Horizontal");
        float translationZ = Input.GetAxis("Vertical");

        Vector3 moveDirection = new Vector3(translationX, 0, translationZ);
        moveDirection = cameraTransform.TransformDirection(moveDirection);
        moveDirection *= speed;

        float zoom = moveDirection.y - 0.05f;

        if(Input.GetKey(KeyCode.Q))
        {
            moveDirection.y += zoom;
        }

        if (Input.GetKey(KeyCode.E))
        {
            moveDirection.y -= zoom;
        }

        characterController.Move(moveDirection);

        if (Input.GetMouseButtonDown(1))
        {
            isRotating = true;
        }

        if (Input.GetMouseButtonUp(1))
        {
            isRotating = false;
        }


        if (isRotating)
        {
            float mouseX = Input.GetAxis("Mouse X");
            float mouseY = Input.GetAxis("Mouse Y");

            // 마우스 입력을 이용하여 회전 각도 계산
            float rotationX = cameraTransform.localEulerAngles.y + mouseX * sensitivity;
            float rotationY = cameraTransform.localEulerAngles.x - mouseY * sensitivity;

            // 회전 각도를 적용 (카메라 또는 플레이어 오브젝트에 따라 다를 수 있음)
            cameraTransform.localEulerAngles = new Vector3(rotationY, rotationX, 0);
        }