Mathf.Sign( float value )
: 값의 부호(+, -)를 판단해서 값이 0 또는 양수면 1, 음수면 -1을 반환한다.
value > 0 → +1
value < 0 → -1
value == 0 → +1 (음수아님, 주의!)
실전 사용 예 (방향 판단)
public void Shoot()
{
GameObject arrow = Instantiate(arrowPrefab, transform.position, Quaternion.identity);
Rigidbody2D rb = arrow.GetComponent<Rigidbody2D>();
float direction = Mathf.Sign(transform.localScale.x);
// 캐릭터 방향에 따라 화살 방향도 따라가게
Vector2 arrowScale = arrow.transform.localScale;
arrowScale.x = Mathf.Abs(arrowScale.x) * direction;
arrow.transform.localScale = arrowScale;
rb.velocity = new Vector2(direction * speed, rb.velocity.y);
}
실전 사용 예 (이동 방향)
현재 이동 방향만으로 방향 판단 (왼쪽이면 -1, 오른쪽이면 1)
void ChaseTarget()
{
Vector2 direction = (target.position - transform.position).normalized;
float dir = Mathf.Sign(direction.x);
Vector2 chaseScale = transform.localScale;
chaseScale.x = Mathf.Abs(chaseScale.x) * dir;
transform.localScale = chaseScale;
enemy.rb2d.MovePosition(enemy.rb2d.position + direction * (speed * Time.fixedDeltaTime));
}
'Unity' 카테고리의 다른 글
[Unity] Enum 모든 값을 가져오기 (0) | 2025.05.15 |
---|---|
[Unity] Layout Group 시리즈(Horizontal, Vertical, Grid) (0) | 2025.05.14 |
오브젝트가 화면을 나가면 사라지게 하기(OnBecameInvisible) (0) | 2025.05.13 |
[유니티] Mathf.Abs를 통한 방향 전환 (0) | 2025.05.12 |
[Unity] JSON 파싱하기(JsonUtility, Newtonsoft.Json) (1) | 2025.05.09 |