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

时间:2018-05-28 10:53:58

标签: c++ xcode sdl sdl-image

我正在观看在SDL游戏中添加图像的教程,但作者使用的是Visual Studio。我在XCode上,我不知道在哪里添加资产文件夹。我尝试右键单击应用程序的根目录> Add files to "Project"> assets文件夹的目的地,但图片未显示在窗口中。

的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);
}

1 个答案:

答案 0 :(得分:1)

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

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