1. 과제
2. 아이디어
3. Mathf.Clamp()
4. 구현코드, 시연영상

 

📝 과제

: 카메라가 플레이어를 따라다니되 맵 범위를 벗어나지 않는 카메라를 구현했다.

예시영상

📝 아이디어

: 맵이 직사각형일 때 , 왼쪽 아래의 x, y값(최솟값)과 오른쪽 위의 x, y값 (최댓값)을 구하 카메라가 그 위치를 넘지않으면 되지 않을까?

 

📝 x 범위

: 최소 "왼쪽 아래 x 값 + 8.8" ~ 최대 "오른쪽 위 x 값 - 8.8" 

 

📝 y 범위

: 최소 "왼쪽 아래 y 값 + 5" ~ 최대 "오른쪽 위 y 값 - 5" 

 

📝 Mathf.Clamp(값, 최소값, 최대값)

: Mathf.Clamp()를 사용하면 쉽게 최소값과 최대값 사이의 결과를 받을 수 있다.

🔖 주어진 값이 최솟값보다 작으면 최솟값 return

🔖 주어진 값이 최댓값보다 크면 최댓값 return

 

Mathf.Clamp(float value, float min, float max);

□ 파라미터

           value : 최소값과 최대값으로 정의된 범위 내에서 제한할 부동 소수점 값 

 

           min : 비교할 최소 부동 소수점 값

           max : 비교할 최대 부동 소수점 값

 

📝 실제 구현

- 필드

 [Header("===Camera===")]
 [SerializeField] private Transform _camera;         // 카메라 
 [SerializeField] private Transform _playerTrs;

 [Header("===Map Edge===")]
 [SerializeField] private Transform _leftDownEdge;   // 왼쪽 아래
 [SerializeField] private Transform _rightUpEdge;    // 오른쪽 위

 

- Start/Update

 private void Start()
 {
     _playerTrs = PlayerManager.Instnace.playerTrs;

 }

 private void LateUpdate()
 {
     F_CheckLimitAndFollow();
 }

 

- F_CheckLimitAndFollow()

 private void F_CheckLimitAndFollow() 
 {
     // x와 y 위치를 각각 제한
     float clampedX = Mathf.Clamp(_playerTrs.position.x,
         _leftDownEdge.position.x + halfWidth,
         _rightUpEdge.position.x - halfWidth);

     float clampedY = Mathf.Clamp(_playerTrs.position.y,
         _leftDownEdge.position.y + halfHeight,
         _rightUpEdge.position.y - halfHeight);

     // 최종 카메라 위치 설정
     _camera.position = new Vector3(clampedX, clampedY, 0);

🔖Mathf.Clamp()로 x와 y의 위치를 제한했다.

 

- 구현이 잘 된 모습을 볼 수 있다!

 


-  유니티 Mathf.Clamp() 공식문서

https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Mathf.Clamp.html

 

Unity - Scripting API: Mathf.Clamp

Returns the minimum value if the given float value is less than the minimum. Returns the maximum value if the given value is greater than the maximum value. Use Clamp to restrict a value to a range that is defined by the minimum and maximum values. Returns

docs.unity3d.com

 


https://github.com/kimYouChae/Sparta_Metaverse

 

GitHub - kimYouChae/Sparta_Metaverse

Contribute to kimYouChae/Sparta_Metaverse development by creating an account on GitHub.

github.com

+ Recent posts