07
22

Clamp 함수

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

주어진 값(value)을 최소값(min)과 최대값(max) 사이로 제한한다.
만약 값이 최소값보다 작으면 최소값으로, 최대값보다 크면 최대값으로 제한된다.
float health = 80f;
float minHealth = 0f;
float maxHealth = 100f;

// health 값을 0부터 100 사이로 제한
float clampedHealth = Mathf.Clamp(health, minHealth, maxHealth);
Debug.Log(clampedHealth); // Output: 80
using UnityEngine;

public class MouseRotation : MonoBehaviour
{
    public Transform playerTransform;  // 플레이어의 Transform 컴포넌트

    public float rotationSpeed = 5f;   // 회전 속도
    public float minRotation = -90f;   // 최소 회전 각도
    public float maxRotation = 90f;    // 최대 회전 각도

    private float currentRotation = 0f; // 현재 회전 각도

    private void Update()
    {
        // 마우스 입력을 받아 회전 각도를 계산
        float mouseDelta = Input.GetAxis("Mouse X") * rotationSpeed;
        currentRotation += mouseDelta;

        // 회전 각도를 최소값과 최대값 사이로 제한
        currentRotation = Mathf.Clamp(currentRotation, minRotation, maxRotation);

        // 회전을 적용하여 플레이어 주변을 회전
        transform.rotation = Quaternion.Euler(0f, currentRotation, 0f);
    }
}

Round 함수

static float Round(float f)

주어진 값(f)을 가장 가까운 정수로 반올림한다.
float num = 3.7f;
float roundedNum = Mathf.Round(num);
Debug.Log(roundedNum); // Output: 4

Ceil 함수

static float Ceil(float f)

주어진 값(f)의 소숫점 첫 번째 자리에서 올림하여 반환한다.
float num = 3.2f;
float ceilNum = Mathf.Ceil(num);
Debug.Log(ceilNum); // Output: 4

Floor 함수

static float Floor(float f)

주어진 값(f)의 소숫점 첫 번째 자리에서 내림하여 반환한다.
float num = 3.8f;
float floorNum = Mathf.Floor(num);
Debug.Log(floorNum); // Output: 3

Abs 함수

static float Abs(float f)

주어진 값(f)의 절댓값을 반환한다.
float num = -5.6f;
float absoluteNum = Mathf.Abs(num);
Debug.Log(absoluteNum); // Output: 5.6

Approximately 함수

static bool Approximately(float a, float b)

두 값(a, b)이 거의 같은지(유한 소수점 오차로 인해 동일한 경우)를 확인하여 참 또는 거짓을 반환한다.
float num1 = 0.1f + 0.2f;
float num2 = 0.3f;
bool isApproximatelyEqual = Mathf.Approximately(num1, num2);
Debug.Log(isApproximatelyEqual); // Output: True

Deg2Rad 함수

static float Deg2Rad

각도를 라디안 값으로 변환한다. (각도 * Mathf.PI / 180)

 

float degree = 90f;
float radian = degree * Mathf.Deg2Rad;
Debug.Log(radian); // Output: 1.5707964 (π/2)

Rad2Deg 함수

static float Rad2Deg

라디안 값을 각도로 변환한다. (라디안 * 180 / Mathf.PI)
float radian = Mathf.PI;
float degree = radian * Mathf.Rad2Deg;
Debug.Log(degree); // Output: 180

PingPong 함수

static float PingPong(float t, float length)

주어진 시간(t)을 0부터 length까지 반복하여 진행하고 다시 length부터 0까지 역방향으로 진행하는 함수이다.
즉, t가 0에서 시작하여 length에 도달하면 다시 역방향으로 되돌아간다.
캐릭터가 특정 구간을 왔다 갔다 반복하는 움직임을 구현하고자 할 때, PingPong 함수를 사용할 수 있다.
캐릭터가 지정한 두 지점 사이를 오가는 움직임을 표현해보면 아래 예제 코드와 같다.
using UnityEngine;

public class CharacterMovement : MonoBehaviour
{
    public float startPoint = 0f; // 시작 지점
    public float endPoint = 10f;  // 끝 지점
    public float speed = 2f;      // 이동 속도

    private float time = 0f;

    private void Update()
    {
        // 시간을 누적하여 이동 위치 계산
        time += Time.deltaTime * speed;
        // PingPong 함수를 사용하여 현재 위치 계산
        float positionX = Mathf.PingPong(time, endPoint - startPoint) + startPoint;

        // 이동할 위치를 설정
        Vector3 newPosition = new Vector3(positionX, transform.position.y, transform.position.z);
        // 캐릭터를 이동할 위치로 이동시킴
        transform.position = newPosition;
    }
}
// startPoint와 endPoint 사이를 오가면서 캐릭터를 이동
// Update 함수에서 Time.deltaTime을 이용하여 시간을 누적하고, 이 누적된 시간을 PingPong 함수에 전달하여 시작 지점과 끝 지점 사이를 왕복하는 값을 계산
// 이렇게 계산된 위치를 캐릭터의 x 좌표로 설정하여 캐릭터가 왕복하는 움직임을 구현

Repeat 함수

static float Repeat(float t, float length)

주어진 시간(t)을 0부터 length까지 반복하여 진행한 후, 다시 0부터 시작하는 함수이다.
주어진 값을 최솟값과 최댓값 사이에서 반복적으로 반복시킬 때 유용하다.
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float rotationSpeed = 100f;

    private float currentAngle = 0f;

    private void Update()
    {
        // 플레이어의 입력을 받아서 회전 시키기
        float rotateInput = Input.GetAxis("Horizontal");
        float rotateAmount = rotateInput * rotationSpeed * Time.deltaTime;

        // 회전한 각도 더하기
        currentAngle += rotateAmount;

        // Mathf.Repeat 함수를 사용하여 0도부터 360도 사이의 값으로 유지하기
        currentAngle = Mathf.Repeat(currentAngle, 360f);

        // 플레이어의 각도 업데이트
        transform.rotation = Quaternion.Euler(0f, currentAngle, 0f);
    }
}
// 플레이어의 입력을 받아서 회전을 시키고, 회전한 각도를 currentAngle 변수에 누적
// Mathf.Repeat 함수를 사용하여 currentAngle 값을 0도부터 360도 사이로 유지하도록 처리
// 플레이어의 회전이 반복적으로 유지되며, 원형 범위 내에서 동작

DeltaAngle 함수

public static float DeltaAngle(float current, float target);

두 각도를 입력으로 받아서 두 각도 사이의 최소 각도 차이를 반환한다.
각도는 일반적으로 -180도부터 180도까지의 범위를 가지며,
이 범위 안에서 가장 최소로 회전하여 목표 각도에 도달하는 방향과 크기를 나타낸다.
current: 현재 각도를 나타내는 값, target: 목표 각도를 나타내는 값
회전 관련 계산이나 방향을 조정하는 등의 상황에서 유용하게 사용될 수 있다.
예제 코드 1
: 캐릭터가 특정 방향을 향해 회전해야 할 때, 부드럽게 목표 방향으로 회전하도록 구현
public Transform target;
public float rotationSpeed = 5f;

void Update()
{
    Vector3 directionToTarget = target.position - transform.position;
    float targetAngle = Mathf.Atan2(directionToTarget.y, directionToTarget.x) * Mathf.Rad2Deg;
    float currentAngle = Mathf.DeltaAngle(transform.eulerAngles.z, targetAngle);

    transform.Rotate(0, 0, currentAngle * rotationSpeed * Time.deltaTime);
}
예제 코드 2
: 카메라가 특정 대상을 따라다니며 시점을 전환할 때,
현재 각도와 목표 각도 사이의 차이를 구해 부드럽게 전환하도록 구현
public Transform target;
public Transform firstPersonCamera;
public Transform thirdPersonCamera;
public float cameraSwitchSpeed = 5f;

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        // 현재 시점과 목표 시점의 각도 차이를 구한다.
        float currentAngle = Mathf.DeltaAngle(transform.eulerAngles.y, thirdPersonCamera.eulerAngles.y);

        if (currentAngle < 0)
        {
            // Third Person 시점으로 전환
            StartCoroutine(SwitchCamera(firstPersonCamera, thirdPersonCamera));
        }
        else
        {
            // First Person 시점으로 전환
            StartCoroutine(SwitchCamera(thirdPersonCamera, firstPersonCamera));
        }
    }
}

IEnumerator SwitchCamera(Transform from, Transform to)
{
    float elapsedTime = 0f;

    while (elapsedTime < 1f)
    {
        elapsedTime += Time.deltaTime * cameraSwitchSpeed;
        transform.rotation = Quaternion.Lerp(from.rotation, to.rotation, elapsedTime);
        yield return null;
    }
}
COMMENT