TIL
랜덤한 방향성 부여하기
박민혁_kog
2023. 11. 8. 20:38
Random.insideUnitCircle
Unity에서 제공하는 랜덤 벡터를 생성하는 함수
이 함수는 2D 공간에서 반지름이 1인 원 내부에 있는 랜덤한 점을 나타내는 2D 벡터를 반환 해줌.
반지름이 1인 원 내부에 있는 임의의 점을 랜덤하게 선택.
이 점의 x와 y 좌표를 가지고 있는 2D 벡터를 생성.
생성된 벡터의 길이는 1 이하.
normalized를 하여 벡터를 정규화 해줘야함
정규화는 벡터 길이가 1 이어야 방향에 따른 이동 속도가 같아진다 (안하면 대각선 이동시 위로는 1속도 오른쪽으론 1.2 속도 로인해 오른쪽으로 좀더 많이 가는 현상이 발생함)
- Vector2 randomPosition = Random.insideUnitCircle;
public class MoveDice : MonoBehaviour
{
private float minForce = 3f;
private float maxForce = 7f;
private Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
float rotationAmount = Random.Range(minRotation, maxRotation);
transform.Rotate(0f, 0f, rotationAmount);
}
void Start()
{
ApplyRandomForce();
//여러번 호출하여 비슷한위치에서 여러번 흔들수도 있을듯함
}
void ApplyRandomForce()
{
//방향성 랜덤받기
Vector2 randomDirection = Random.insideUnitCircle.normalized;
//랜덤힘
float randomForce = Random.Range(minForce, maxForce);
//랜덤 방향으로 랜덤의 힘을 줌
rb.AddForce(randomDirection * randomForce, ForceMode2D.Impulse);
}
}