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));
    }

+ Recent posts