簡體   English   中英

精靈的 SFML 向量和精靈碰撞錯誤

[英]SFML Vector of sprites and Sprite Collision Error

我正在用 C++ 和 SFML 制作游戲,但我遇到了一個嚴重的問題。 我想要做的是,當我的玩家(又名人類角色)與一個項目發生碰撞時,只有那個項目應該被刪除。 例如,當玩家與“chicken”項目發生碰撞時,只有“chicken”項目應該被刪除,而不是其他項目。 但是,當我運行我的程序時,當玩家與“雞”項目發生碰撞時,其他項目都會被刪除。 我不知道為什么。 我真的需要你的幫助。 盡管我的英語很差,但感謝您的閱讀!

這是我的代碼:

     #include <SFML/Graphics.hpp>
     ...
     using namespace std;
     using namespace sf;
     ...

     int main () {
     ...

     //item Sprites

     Texture bombTex;
     bombTex.loadFromFile("images/bomb.png");
     Sprite bomb;
     ...
     Texture bomb2Tex;
     bomb2Tex.loadFromFile("images/bomb_2.png");
     Sprite bomb_2;
     ...
     Texture cakeTex;
     cakeTex.loadFromFile("images/cake.png");
     Sprite cake;
     ...
     Texture coffeeTex;
     coffeeTex.loadFromFile("images/coffee.png");
     Sprite coffee;
     ...
    Texture chickenTex;
    chickenTex.loadFromFile("images/chicken.png");
    Sprite chicken;
    ...
    Texture pizzaTex;
    pizzaTex.loadFromFile("images/pizza.png");
    Sprite pizza;

    //item array (I made an item array to display & render various items in the game screen.)
    Sprite item[10];
    item[0] = bomb;
    item[1] = coffee;
    item[2] = bomb_2;
    item[3] = chicken;
    item[4] = pizza;

    std::vector<Sprite> items;
    items.push_back(Sprite(item[4]));

    ...

   while (window.isOpen())
  {   ...
      ...
    for (size_t i = 0; i < items.size(); i++)
    {
        if (humanArr[index].getGlobalBounds().intersects(item[i].getGlobalBounds())) 
        //humanArr[index] is a player Sprite.
        {
            ...
            items.erase(items.begin());
        }
     }
    ...
   window.clear();
    ...
   for (size_t i = 0; i < items.size(); i++)
        {
            window.draw(item[i]);
        }

    ...
   window.display();
   }
   return 0;
}
    for (size_t i = 0; i < items.size(); i++)
    {
        // first problem: you are accessing item[i] instead of items[i]
        if (humanArr[index].getGlobalBounds().intersects(item[i].getGlobalBounds())) 
        {
            ...
            items.erase(items.begin()); // <---------- second problem is here
        }
     }

您不是在擦除正在迭代的項目,而是在擦除第一個項目。 您還訪問了錯誤的數組。 我建議更改item的名稱以避免將來出現這種情況。 這是解決此問題的方法:

    // Pull human bounds out of the loop so that we dont' access them each
    // iteration.
    const humanBounds = humanArr[index];
    for (auto iter = items.begin(); iter != items.end();)
    {
        if (humanBounds.intersects(iter->getGlobalBounds()))
        {
            iter = items.erase(iter); 
        }
        else
        {
            ++iter;
        }
    }

有關更多信息,請參見std::vector::erase

暫無
暫無

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

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