Пытаясь создать квадраты в ряд под указанным углом, каким-то образом создали спираль Фибоначчи - PullRequest
0 голосов
/ 28 апреля 2019

Моя программа в идеале создаст серию сложенных квадратов на основе 2 переменных. 1 - количество квадратов в серии, а другое - количество серий. каждая серия ответвляется от центра экрана под разными углами, разнесенными равномерно друг от друга. Если есть 2 серии, один будет смотреть на 0 градусов, а другой будет на 180 градусов. Если будет 3, то первый будет смотреть на 0 градусов, второй - на 120, а третий - на 240. Где-то в моей математике или в моем методе создания этого эффекта я ошибся.

Текущий результат по какой-то причине - спираль Фибоначчи. Вот Подозреваемые функции ниже (со всеми определениями переменных) Кроме того, кнопка это класс, который я сделал, а не опечатка:

public button Led; //Object used to create series
public Slider ledNumber;// controls how many LEDS there are per series
public Slider IncrementsPerRotation;//Controls how many series there are
public Text ledText;//text above ledNumber slider
public Text incrementText;//text above IncrementsPerRotation Slider
public Transform canvas;//Canvas where objects will be created
List<List<button>> LedConfig = new List<List<button>>();//where all the LEDs will be stored
private float buttonW, middleX,middleY; // the width of the LED and the middle values of the screen
private int prevLed = 0, prevIncrements = 0;// previous values for both sliders
// Start is called before the first frame update
void Start()
{
    buttonW = Led.transform.localScale.x;// set LED width
    Vector2 temp = Camera.main.ScreenToWorldPoint(new Vector2 (Screen.width / 2, Screen.height / 2));// get middle values

    //assign middle values
    middleX = temp.x;
    middleY = temp.y;
}

// Update is called once per frame
void Update()
{

    if (prevLed != (int)ledNumber.value && (int)ledNumber.value > 0)//has the slider changed and is it positive
    {
        Debug.Log("prevLED Changed");
        if (prevLed < ledNumber.value)// am I removing or adding buttons
        {
            Debug.Log("Adding LED");
            for (int x = 0; x < (int)ledNumber.value - prevLed; ++x)//for the difference in the number changed
            {
                for (int y = 0; y < IncrementsPerRotation.value; y++)//add a led to the top row
                {
                    float angle = 360 / IncrementsPerRotation.value * y;// get angle

                    // if there isnt enough lists, add another one;
                    if(LedConfig.Count-1 < y)
                    {
                        LedConfig.Add(new List<button>());
                        ++prevIncrements;
                    }

                    //object: LED Where: (see GetPos) What angle: angle converted to radians
                    LedConfig[y].Add(Instantiate(Led, GetPos(y, angle), new Quaternion(Quaternion.identity.x, Quaternion.identity.y, angle * (Mathf.PI / 180f), Quaternion.identity.w),canvas));
                    Debug.Log("got past instantiate");
                }
                ++prevLed;
                Debug.Log("end of outer for loop");
            }
        }
        else
        {
            Debug.Log("Removing LED");
            for (int x = 0; x < prevLed - (int)ledNumber.value; ++x)//for the difference in the number changed
            {
                for (int y = 0; y < LedConfig.Count; y++)//delete the top row of LEDs
                {
                    LedConfig[y][LedConfig[y].Count - 1].delete();//delete the LED
                    LedConfig[y].RemoveAt(LedConfig[y].Count - 1);//remove it from the list
                }
                --prevLed;
                Debug.Log("end of outer for loop");
            }
        }
    }
    if (prevIncrements != (int)IncrementsPerRotation.value && (int)IncrementsPerRotation.value > 0)
    {
        deleteAll();
        prevLed = 0;
    }
}
void deleteAll()
{
        for (int x = 0; x < LedConfig.Count; ++x)//for the difference in the number changed
        {
            for (int y = 0; y < LedConfig[x].Count; y++)//delete the top row of LEDs
            {
                LedConfig[y][LedConfig[y].Count - (y + 1)].delete();//delete the LED
                LedConfig[y].RemoveAt(LedConfig[y].Count - (y + 1));//remove it from the list
            }
        }
}

private Vector2 GetPos(int a,float angle)
{
    float angleInRadians = angle * (Mathf.PI / 180f);
    ++a;


    Debug.Log("x " + (buttonW * a) * (Mathf.Sin(angleInRadians) * 180 / Mathf.PI));
    Debug.Log("y " + (buttonW * a) * (Mathf.Cos(angleInRadians) * 180 / Mathf.PI));
    Debug.Log("middleX " + middleX);
    Debug.Log("middleY " + middleY);
    Debug.Log("tot X " + (middleX + buttonW * a * Mathf.Sin(angleInRadians)));
    Debug.Log("tot Y " + (middleY + buttonW * a * Mathf.Cos(angleInRadians)));

    return new Vector2(middleX + buttonW * a * Mathf.Sin(angleInRadians), middleY + buttonW * a * (Mathf.Cos(angleInRadians)));
}

В коде много ошибок: Перемещение ledNumber создает несколько квадратов в одном месте

Перемещение IncrementsPerRotations приводит к ошибке индекса вне диапазона, которая ставит игру на паузу, если игра продолжается (нажатием кнопки паузы), создается спираль Фибоначчи с квадратами, а квадраты находятся под случайными углами.

Это не весь код, а только та часть, которая связана с ошибкой.

Редактировать: Здесь - наглядное пособие о том, как должен выглядеть желаемый результат при увеличении значений вращения на 1-4 и числа светодиодов при 3

.
...