Mathf.Clamp() : 값을 특정 범위 내로 제한할 때 사용됩니다.
이 함수는 주어진 값이 최소값과 최대값 사이에 있도록 값을 제한(clamp)하는 데 사용됩니다.
public static float Clamp(float value, float min, float max);
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으로 제한됩니다.
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);
}
}
유니티 기본 C# 스크립트 내용 수정하기(start,update) (0) | 2024.08.29 |
---|---|
유니티 3D 비행기(캐릭터) 상하좌우 움직이기 (0) | 2024.08.29 |
유니티 오브젝트 상하좌우로 왔다갔다 하기 (0) | 2024.08.27 |
유니티 다음 씬으로 넘어가기, 현재 씬 인덱스 구하기 (0) | 2024.08.26 |
유니티 특정 상황에서 씬 다시 불러오기, 재시작 (0) | 2024.08.26 |