簡體   English   中英

如何編輯向量內的 SDL_Rect 的寬度、高度、xpos 和 ypos<sdl_rect></sdl_rect>

[英]How do I edit the width, height, xpos and ypos of a SDL_Rect that is inside a vector<SDL_Rect>

//all the variable needed
vector<SDL_Rect> middleBox;
SDL_Rect firstBox, lastBox;
char userInput

void switchBoxes()//program closes as soon as it get here
{
    for(int i = 0; i < 100; i++)
    {
        if(i = 0)
            middleBox.at(i) = firstBox;
        else 
            middleBox.at(i) = middleBox.at(i - 1);  
    }

}

init main() 
{
    firstBox.x = 10; 
    firstBox.y = 10;
    firstBox.w = 17;
    firstBox.h = 17;

    do 
    {    
        firstBox.x += 10; //so first box is moving 
        middleBox.push_back({firstBox.x - 17, firstBox.y, 17, 17 });//create new box
        switchBoxes(); //this function would idealy make every box follow

        //draw firstbox
        SDL_SetRenderDrawColor(renderer, 0, 102, 0, 1);
        SDL_RenderDrawRect(renderer, &snake);
        SDL_RenderFillRect(renderer, &snake);

        //draw the box just created
        for(auto & lastBox:middleBox)
        {
            SDL_RenderDrawRect(renderer, &snakeTail);
            SDL_RenderFillRect(renderer, &snakeTail);
        }
    } while(userInput != 'q');

    return 0;
}

我想要我的代碼做什么:

  1. 渲染 box1 假設在 (10, 10)
    .
  2. 然后box1被移動到其他地方
  3. 在box1后面的向量(box2)內渲染另一個框
  4. 將 box2 移動到 box1 的當前位置
    .
  5. 將 box1 移動到某處
  6. 將 box2 移動到 box1 的當前位置
  7. 在box1后面的向量(box3)內渲染另一個框
  8. 將 box3 移動到 box2 的當前位置

等等.....

一切正常,直到 function switchBoxes() 每次我到那里,程序都會關閉。

如何編輯矢量<SDL_Rect>內的SDL_Rect寬度、高度、xposypos

編輯:或者是否有另一種方法可以創建矩形並在第一個矩形移動時讓它們相互跟隨

我沒有使用 SDL,但導致您出現問題的一件事是向量超出了 switchBoxes() function 內的 for 循環的范圍。 迭代向量的大小更安全。 if 條件也應該使用“==”。

嘗試:

for(int i = 0; i < middleBox.size(); i++)
    {
        if(i == 0)
            middleBox[i] = firstBox;
        else 
            middleBox[i] = middleBox[i - 1];  
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM