본문 바로가기

Unity

[Unity] 반지름 R인 원 위에 일정 간격(각도)의 위치 얻기.

using UnityEngine;

public class CubeCreator : MonoBehaviour
{
    [SerializeField] GameObject _cubePrefab = null;
    void Start()
    {
        CreateCubes();
    }

    public void CreateCubes()
    {
        int radius = 5;             //반지름
        int angle = 30;             //간격 각도
        int loop = 360 / angle;     //반복 횟수 = 360 / 각도

        int currentAngle = 0;
        for (int i = 0; i < loop; i++)
        {
            Vector3 pos = new Vector3(Mathf.Cos(currentAngle * Mathf.Deg2Rad) * radius, Mathf.Sin(currentAngle * Mathf.Deg2Rad) * radius, 0);
            Transform cube = GameObject.Instantiate(_cubePrefab).transform;
            cube.position = pos;

            //오브젝트가 센터를 바라보게 하고 싶을 경우.
            Quaternion look = Quaternion.LookRotation(pos);
            cube.rotation = look;

            currentAngle += angle;
        }
    }
}

radius : 센터로 부터 떨어진 거리

angle : 배치할 오브젝트간의 간격 각도

loop : 배치할  오브젝트의 수 (angle의 값이 크면 수가 작아지고, angle의 값이 작으면 수가 많아진다.)

일정 거리(radius) 만큼 떨어진 거리에 일정한 각도(angle)로 오브젝트 배치.

 

오브젝트가 센터를 바라보게 했을 경우.