SFML平台在c++中使用贴图

SFML platformer using tile map in c++

本文关键字:平台 c++ SFML      更新时间:2023-10-16

嗨,我有一个类我的映射,它是绘制到屏幕上,但它只绘制垂直向下的窗口左侧。我能找出我哪里出错了。任何帮助都将非常感激。我很确定这和我在draw函数中的for循环有关。

void Map::Initialise(const char *filename)
{
     std::ifstream openfile(filename);
     std::string line;
     std::vector <int>  tempvector;
    while(!openfile.eof())
    {
        std::getline(openfile, line);
        for(int i =0; i < line.length(); i++)
        {
            if(line[i] != ' ') // if the value is not a space
            {
                char value[1] = {line[i]}; // store the character into the line variable
                tempvector.push_back(atoi(value)); // then push back the value stored in value into the temp vector
            }
            mapVector.push_back(tempvector); // push back the value of the temp vector into the map vector
            tempvector.clear(); // clear the temp vector readt for the next value
        }
    }
}

void Map::DrawMap(sf::RenderWindow &Window)
{
    sf::Shape rect = sf::Shape::Rectangle(0, 0, BLOCKSIZE, BLOCKSIZE, sf::Color(255, 255, 255, 255));
    sf::Color rectCol;
    sf::Sprite sprite;
    for(int i = 0; i < mapVector.size(); i++)
    {
        for(int j = 0; j < mapVector[i].size(); j++)
        {
            if(mapVector[i][j] == 0)
               rectCol = sf::Color(44, 117, 255);
            else if (mapVector[i][j] == 1)
                rectCol = sf::Color(255, 100, 17);
            rect.SetPosition(j * BLOCKSIZE, i * BLOCKSIZE);
            rect.SetColor(rectCol);
            Window.Draw(rect);
        }
    }
}

首先,使您的提取while循环的条件:

while(std::getline(openfile, line))
{
  // ...
}

使用openfile.eof()是一个非常糟糕的主意;仅仅因为您还没有到达文件的末尾,并不意味着下一次提取将会成功。你只是不知道你是否真的有一个有效的line

其次,这将不能正常工作:

char value[1] = {line[i]}; // store the character into the line variable
tempvector.push_back(atoi(value));

我可以看到你为什么使用char[1] -你想把它转换成一个指针,因为atoi需要一个const char*。然而,atoi也期望它所指向的数组以空结束。你的不是。这只是一个char

有一种更好的方法将char(一个数字)转换为它所代表的整数。所有数字字符的值保证是连续的:

char value = line[i];
tempvector.push_back(value - '0');

现在,真正的问题来了。在读取一个字符后,将tempvector推入mapVector。您需要将它移到for循环之外的行:

while(std::getline(openfile, line))
{
    for(int i =0; i < line.length(); i++)
    {
        // ...
    }
    // Moved here
    mapVector.push_back(tempvector); // push back the value of the temp vector into the map vector
    tempvector.clear(); // clear the temp vector readt for the next value
}