【发布时间】:2014-09-19 10:42:13
【问题描述】:
在开始之前,我使用的 IDE 是 Code::Blocks。
我打算在与我的学习项目不同的另一个项目中练习我在网上学到的关于 SDL 的知识。我想在背景上加载一个球的图像。它在我的学习项目中运行良好。我将代码复制到我的测试项目中,球消失了。只有背景是可见的。
我删除了涉及背景的代码,它工作正常。
我的代码:
#include <iostream>
#include <cstdlib>
#include <SDL.h>
#include <SDL_image.h>
#undef main
using namespace std;
SDL_Texture *LoadTexture (string filepath, SDL_Renderer *renderTarget){
SDL_Texture *texture = 0;
SDL_Surface *surface = IMG_Load(filepath.c_str());
texture = SDL_CreateTextureFromSurface(renderTarget, surface);
SDL_FreeSurface(surface);
return texture;
}
int main () {
SDL_Window *window = 0;
SDL_Texture *ball = 0;
SDL_Texture *background_sky = 0;
SDL_Renderer *renderTarget = 0;
int frameW, frameH;
int textureW, textureH;
//--Crop Instructions--//
frameW = textureW / 1; //row division
frameH = textureH / 1; //column division
SDL_Rect ballcrop;
ballcrop.x = ballcrop.y = 0;
ballcrop.w = frameW; //length of selected area
ballcrop.h = frameH; //height of selected area
SDL_Rect ballpos;
ballpos.x = ballpos.y = 10; //ball position
ballpos.w = ballpos.h = 64; //size of crop
//---------------------//
SDL_Init(SDL_INIT_EVERYTHING);
IMG_Init(IMG_INIT_PNG);
window = SDL_CreateWindow("Ball", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 500, 500, SDL_WINDOW_SHOWN);
renderTarget = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
ball = LoadTexture("ball.png", renderTarget);
background_sky = LoadTexture("bg_sky.png", renderTarget);
SDL_QueryTexture(ball, NULL, NULL, &textureW, &textureH); //crop action
bool Active = true;
SDL_Event ev;
while (Active) {
while (SDL_PollEvent(&ev)!=0) {
if (ev.type == SDL_QUIT)
Active = false;
else if (ev.type == SDL_KEYDOWN) {
switch (ev.key.keysym.sym) {
case SDLK_UP:
ballpos.y -= 5;
break;
case SDLK_DOWN:
ballpos.y += 5;
break;
}
}
}
SDL_RenderClear(renderTarget);
SDL_RenderCopy(renderTarget, background_sky, NULL, NULL);
SDL_RenderCopy(renderTarget, ball, &ballcrop, &ballpos);
SDL_RenderPresent(renderTarget);
}
SDL_DestroyWindow(window);
SDL_DestroyTexture(background_sky);
SDL_DestroyTexture(ball);
SDL_DestroyRenderer(renderTarget);
window = 0;
ball = background_sky = 0;
renderTarget = 0;
IMG_Quit();
SDL_Quit();
return 0;
}
我不想展示我的研究项目的源代码,因为它非常很乱。
任何帮助将不胜感激:)
【问题讨论】:
-
如果只注释掉与背景关联的
SDL_RenderCopy,还能用吗?当您颠倒SDL_RenderCopys 的顺序时,同样的问题? -
frameW = textureW / 1;除以 1 有什么意义?另外,您在哪里获得 textureW 的值...在发布的代码中它没有显示它。 -
@MicroVirus :是的。背景消失了,但球不在那里。我必须注释掉所有与 bg 相关的代码
-
@zammalad : 这是一件很细致的事情^^;
-
我认为最好是使用调试器逐行逐行检查它,以查看实际发生故障的行:是
SDL_RenderCopy失败了,还是球纹理没有(正确)加载开始?
标签: c++ sdl codeblocks sdl-2