gpt4 book ai didi

c++ - SDL,如何渲染背景图片?

转载 作者:行者123 更新时间:2023-11-28 06:48:54 38 4
gpt4 key购买 nike

我有一个渲染问题,但我已经解决了。问题是,图片实际上不会显示。我知道图片已加载,因为如果未加载,我有一个错误处理程序。我知道代码很乱,但我只需要显示图片即可。

#include <SDL/SDL.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

const int fps = 60;

SDL_Window *window;


int main(int argc, char **argv)
{
SDL_Init(SDL_INIT_EVERYTHING);
window = SDL_CreateWindow("", 300, 100, 1024, 800, SDL_WINDOW_OPENGL);

if (window == NULL)
{
cout << ("could not create window: %s/n", SDL_GetError());
return 1;
}
SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0);
int x = 0, y = 0;
SDL_Surface *screen;
SDL_Surface *background = SDL_LoadBMP("hockeyrink.bmp");
if(background == NULL)
{
SDL_ShowSimpleMessageBox(0, "Background init error", SDL_GetError(), window);
}

if(renderer == NULL)
{
SDL_ShowSimpleMessageBox(0, "Renderer init error", SDL_GetError(), window);
}
SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer,background);
if(texture == NULL)
{
SDL_ShowSimpleMessageBox(0, "Texture init error", SDL_GetError(), window);
}

const int speed = 5;
SDL_Rect camera;
camera.x = 0; //Don't worry about this camera, I need this after i get the background working.
camera.y = 0;
camera.w = 800;
camera.h = 600;
bool b[2] = {0,0};
Uint32 start;

bool running = true;
while (running)
{
start = SDL_GetTicks();
SDL_Event event;

while(SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_QUIT:
running = false;
SDL_DestroyTexture(texture);
SDL_FreeSurface(background);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
break;
case SDL_KEYDOWN:
switch(event.key.keysym.sym)
{
case SDLK_UP:
b[0]=1;
break;
case SDLK_LEFT:
b[1]=1;
break;
}
break;
case SDL_KEYUP:
switch(event.key.keysym.sym)
{
case SDLK_UP:
b[0]=0;
break;
case SDLK_LEFT:
b[1]=0;
break;
}
break;
}
}

if(b[0])
{
x+=speed;
camera.y+=speed;
if (camera.y > 3000-800)
{
camera.y=0;
}

}
else if(b[1])
{
x-=speed;
camera.y-=speed;

if (camera.y <= 0)
{
camera.y = 2000-800;
}


SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);
}
if(1000/fps>SDL_GetTicks()-start)
{
SDL_Delay(1000/fps-(SDL_GetTicks() - start));
}
}

return 0;
}

最佳答案

您已将 b[1] 初始化为 0 并且仅当 b[1]1< 时才渲染纹理 和你的代码一样。
您应该输入以下行:

SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);

在循环之前,
或按键盘的左键(即 SDLK_LEFT)
在屏幕上渲染和呈现图像。

它适用于我的系统,因此它也应该适用于您的系统。

关于c++ - SDL,如何渲染背景图片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24422358/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com