[유니티] Unity Mathf.Clamp


Mathf.Clamp 란

지정한 value 값이 Min / Max 값을 벗어나지 않게 제어하는 함수입니다.
ex) 카메라가 일정범위안에서만 자유롭게 이동










Mathf.Clamp Min, Max를 사용하면 이동범위 제한이 가능하기 때문에 
카메라나 캐릭터 등 오브젝트가 불필요한 곳으로 이동하는 것을 방지할 수 있습니다.



Mathf.Clamp Script

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public class CameraClamp : MonoBehaviour
{
    public float moveSpeed;
    public float xMin, xMax, yMin, yMax;    

    void Update() {
        if (Input.GetMouseButton(0)) {
            transform.position -= 
                new Vector3(Input.GetAxis("Mouse X") * moveSpeed * Time.deltaTime, 0f, 
                Input.GetAxis("Mouse Y") * moveSpeed * Time.deltaTime);
        }

        float x = Mathf.Clamp(transform.position.x, xMin, yMax);
        float z = Mathf.Clamp(transform.position.z, yMin, yMax);

        transform.position = new Vector3(x, transform.position.y, z);
    }
}

댓글