상세 컨텐츠

본문 제목

유니티 Mathf.Clamp() 특정값을 범위로 제한하기

유니티/기능

by MJ_119 2024. 8. 29. 00:52

본문

Mathf.Clamp() : 값을 특정 범위 내로 제한할 때 사용됩니다.

이 함수는 주어진 값이 최소값과 최대값 사이에 있도록 값을 제한(clamp)하는 데 사용됩니다.

 

public static float Clamp(float value, float min, float max);

 

 

매개변수

  • value: 제한하려는 대상 값입니다.
  • min: 값이 가질 수 있는 최소값입니다.
  • max: 값이 가질 수 있는 최대값입니다.

동작 원리

  • value가 min보다 작으면, Mathf.Clamp()는 min을 반환합니다.
  • value가 max보다 크면, Mathf.Clamp()는 max를 반환합니다.
  • value가 min과 max 사이에 있으면, Mathf.Clamp()는 value를 그대로 반환합니다.

 

float health = 120f;  // 현재 체력
float minHealth = 0f;  // 최소 체력
float maxHealth = 100f;  // 최대 체력

// 체력을 0에서 100 사이로 제한
health = Mathf.Clamp(health, minHealth, maxHealth);

// 출력: health는 100으로 제한됨
Debug.Log("Health: " + health);

 

이 코드에서 health가 120이지만, Mathf.Clamp()에 의해 100으로 제한됩니다. 따라서 결과적으로 health 값은 100이 됩니다.

 

float speed = 15f;  // 플레이어의 현재 속도
float minSpeed = 5f;  // 최소 속도
float maxSpeed = 10f;  // 최대 속도

// 속도를 5에서 10 사이로 제한
speed = Mathf.Clamp(speed, minSpeed, maxSpeed);

// 출력: speed는 10으로 제한됨
Debug.Log("Speed: " + speed);

 

여기서는 speed가 15이지만, Mathf.Clamp() 함수에 의해 최대값인 10으로 제한됩니다.

 

float mouseSensitivity = 3.5f;  // 플레이어가 설정한 마우스 감도
float minSensitivity = 1f;  // 최소 감도
float maxSensitivity = 3f;  // 최대 감도

// 마우스 감도를 1에서 3 사이로 제한
mouseSensitivity = Mathf.Clamp(mouseSensitivity, minSensitivity, maxSensitivity);

// 출력: mouseSensitivity는 3으로 제한됨
Debug.Log("Mouse Sensitivity: " + mouseSensitivity);

 

이 예제에서는 mouseSensitivity가 3.5로 설정되어 있지만, 최대값 3으로 제한되므로 mouseSensitivity는 3이 됩니다.

 

float xPosition = -50f;  // UI 요소의 x 위치
float minX = 0f;  // 최소 x 위치
float maxX = 100f;  // 최대 x 위치

// UI 요소의 x 위치를 0에서 100 사이로 제한
xPosition = Mathf.Clamp(xPosition, minX, maxX);

// 출력: xPosition은 0으로 제한됨
Debug.Log("X Position: " + xPosition);

 

여기서는 xPosition이 -50이지만, 최소값이 0이므로 Mathf.Clamp()에 의해 0으로 제한됩니다.

활용 사례

  • 체력 시스템: 체력을 0에서 최대 체력 값 사이로 제한할 때.
  • 이동 속도 제어: 캐릭터나 오브젝트의 이동 속도를 특정 범위로 제한할 때.
  • 카메라 제어: 카메라의 회전 각도나 위치를 특정 범위로 제한할 때.
  • UI 요소 위치: UI 요소의 위치를 화면 내에서 제한할 때.
  • 변수 값 제한: 입력된 값이 특정 범위를 벗어나지 않도록 할 때.

Mathf.Clamp()는 값이 특정 범위를 벗어나지 않도록 보장할 때 매우 유용합니다. 이 함수를 사용하면 쉽게 값을 안전하게 제한할 수 있어 다양한 게임 로직에서 널리 활용됩니다.

 

 

 

@ 캐릭터가 이동하는데 카메라 화면 안넘어가게 하기

 

using UnityEngine;

public class PlayerFly : MonoBehaviour
{
    float xInput, yInput;

    [SerializeField] float xLimit = 5f;
    [SerializeField] float yLimit = 5f;
    [SerializeField] float playerSpeed = 30f;

    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        movePlayer();

    }

    private void movePlayer()
    {
        xInput = Input.GetAxis("Horizontal");
        yInput = Input.GetAxis("Vertical");

        float X = xInput * Time.deltaTime * playerSpeed;
        float Y = yInput * Time.deltaTime * playerSpeed;

        float moveX = transform.localPosition.x + X;
        float moveY = transform.localPosition.y + Y;

        float clampX = Mathf.Clamp(moveX, -xLimit, xLimit);
        float clampY = Mathf.Clamp(moveY, -yLimit, yLimit);

        transform.localPosition = new Vector3(clampX, clampY, transform.localPosition.z);
    }
}

관련글 더보기