Unity/RPG Project

RPG Project - 16 [ Object 충돌에 따라 카메라 Zoom 구현 ]

SiJun-Park 2024. 10. 23. 03:31

이번 16번째의 목표는 카메라의 Zoom 기능 구현 입니다.

 

마우스 휠로 Zoom을 하는 것이 아닌, 플레이어 기준으로 마우스를 좌우로 이동을 한다고 하였을 때

집, 나무, 벽 등이 있으면 통과를 해버려 보이지 않는 현상이 있습니다.

현재 카메라 위치( 회전으로 집안에 들어감 )
결과

위와같이 카메라가 물체를 통과해서 캐릭터를 바라보게 되는 문제가 있습니다.

 

    public void Rotation(Transform pos)
    {
        x_rotation += Input.GetAxisRaw("Mouse X") * _RotationSensitivity * Time.deltaTime;
        y_rotation += Input.GetAxisRaw("Mouse Y") * _RotationSensitivity * Time.deltaTime;
        y_rotation = Mathf.Clamp(y_rotation, _minRotation, _maxRotation);
        transform.localEulerAngles = new Vector3(-y_rotation, x_rotation, 0);
       // transform.position = pos.position - transform.forward * _CameraDistance;
    }

CameraRotation.cs에선 position을 설정해주는 부분을 주석처리 합니다!

 

    [Header("ZOOM")]
    public float _MinDistance = 2f;
    public float _CameraDistance = 5f;
    public float _ZoomSpeed = 5f;
    private float _CurrentDistance;
    private Vector3 _ZoomPosition;

    public void Zoom(Transform player)
    {
        int Imask = 1 << LayerMask.NameToLayer("House") | 1 << LayerMask.NameToLayer("Wall") | 1 << LayerMask.NameToLayer("Wood");

        RaycastHit hit;
        if (Physics.Raycast(player.transform.position, -transform.forward, out hit, _CameraDistance, Imask))
        {
            _CurrentDistance = Mathf.Clamp(hit.distance, _MinDistance, _CameraDistance);
        }
        else
        {
            _CurrentDistance = Mathf.Lerp(_CurrentDistance, _CameraDistance, _ZoomSpeed * Time.deltaTime);
        }
        _ZoomPosition = player.position - transform.forward * _CurrentDistance;
        transform.position = _ZoomPosition;
    }

Zoom 부분에서는 RayCast를 사용을 해서 만약에 Imask에 해당되는 레이어를 가진 물체가 있다면 

현재거리를 제한을 해줍니다.

 

그게 아니면 다시 서서히 멀어지게 해줍니다.

 

그렇게 해서 포지션을 계산을 하여 카메라의 위치를 다시 잡아줍니다.

 

 

결과