无法在 macOS 上的 SDL 游戏中加载图像

Can't load image in SDL game on macOS

我正在看在SDL游戏中添加图像的教程,但作者使用Visual Studio。我在 XCode 上,但不确定在何处添加资产文件夹。我尝试右键单击应用程序的根 > Add files to "Project" > assets 文件夹的目标,但图像未显示在 window.

main.cpp

#include "Game.hpp"

Game *game = nullptr;

int main() {

    game = new Game();

    game->init("Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, false);

    while (game->running()) {
        game->handleEvents();
        game->update();
        game->render();
    }

    game->clean();

    return 0;
}

这是我在函数末尾添加图像的初始化方法:

Game.cpp

void Game::init(const char *title, int xpos, int ypos, int width, int height, bool fullscreen)
{
    int flags = 0;
    if (fullscreen) {
        flags = SDL_WINDOW_FULLSCREEN;
    }

    if (SDL_Init(SDL_INIT_EVERYTHING) == 0) {
        std::cout << "Subsystems initalized." << std::endl;

        window = SDL_CreateWindow(title, xpos, ypos, width, height, fullscreen);

        if (window)
        {
            std::cout << "Window created!" << std::endl;
        }

        renderer = SDL_CreateRenderer(window, -1, 0);

        if (renderer)
        {
            SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
            std::cout << "Renderer created!" << std::endl;
        }

        isRunning = true;
    } else {
        isRunning = false;
    }

    SDL_Surface *tempSurface = IMG_Load("assets/player.png");
    playerTexture = SDL_CreateTextureFromSurface(renderer, tempSurface);
    SDL_FreeSurface(tempSurface);
}

这是渲染方法:

Game.cpp

void Game::render()
{
    SDL_RenderClear(renderer);
    SDL_RenderCopy(renderer, playerTexture, NULL, NULL);
    SDL_RenderPresent(renderer);
}

感谢 Botje 的评论和 this answer 我解决了问题。我必须设置工作目录以指向我的源文件夹。

如果您有同样的问题,请转到 Product > Scheme > Edit Scheme... > Options,检查 Use custom working directory,单击小文件夹图标并添加您的源目录。