存在多个纹理时SDL闪烁,但仅存在一个纹理时稳定

时间:2019-04-21 18:07:11

标签: c++ textures sdl render free

目前,我实际上是在为任务重新创建原始的Mario。我进行了设置,以便游戏使用ScreenManager,并且当前默认在运行时加载Level1。然后,Level1使用我之前制作的Texture2D类加载背景和角色。如果其中一个已加载而另一个已被注释掉,则它们将在屏幕上正常显示并看上去正常,但是,如果我将它们都在屏幕上渲染,则它将开始连续闪烁。

Level1 Render()函数:

void GameScreenLevel1::Render()
{
    mBackgroundTexture->Render(Vector2D(), SDL_FLIP_NONE);
    myCharacter->Render();
}

Texture2D类:

#include <iostream>
#include <SDL_image.h>
#include "Texture2D.h"
using namespace::std;

Texture2D::Texture2D(SDL_Renderer* renderer)
{
    mRenderer = renderer;
    SDL_Texture* mTexture = NULL;
    SDL_Texture* vTexture = NULL;

    int             mWidth = 0;
    int             mHeight = 0;
}

Texture2D::~Texture2D()
{
    Free();
    mRenderer = NULL;
}

bool Texture2D::LoadFromFile(string path)
{
    Free();

    //Loadtheimage
    SDL_Surface* pSurface = IMG_Load(path.c_str());
    if (pSurface != NULL)
    {
        SDL_SetColorKey(pSurface, SDL_TRUE, SDL_MapRGB(pSurface->format, 0, 0xFF, 0xFF));
        mTexture = SDL_CreateTextureFromSurface(mRenderer, pSurface);

        if (mTexture == NULL)
        {
            cout << "Unable to create texture from surface. Error:" << SDL_GetError() << endl;
        }

        else
        {
            mWidth = pSurface->w;
            mHeight = pSurface->h;
        }
    }

    else
    {
        cout << "Unable to create texture from surface. Error: " << IMG_GetError() << endl;
    }

    //vTexture = mTexture;
    return mTexture != NULL;
}

void Texture2D::Render(Vector2D newPosition, SDL_RendererFlip flip, double angle)
{
    //clear the screen
    SDL_SetRenderDrawColor(mRenderer, 0x00, 0x00, 0x00, 0x00);
    SDL_RenderClear(mRenderer);

    //set where to render the texture
    SDL_Rect renderLocation = {newPosition.x, newPosition.y, mWidth, mHeight};

    //render to screen
    SDL_RenderCopyEx(mRenderer, mTexture, NULL, &renderLocation, 0, NULL, flip);
    SDL_RenderPresent(mRenderer);
}

void Texture2D::Free()
{
    if (mTexture != NULL)
    {
        SDL_DestroyTexture(mTexture);
        mTexture = NULL;
        SDL_DestroyTexture(vTexture);
        vTexture = NULL;
        mHeight = 0;
        mWidth = 0;
    }
}

在我看来,代码正在清理屏幕并在每一帧上渲染纹理,从而导致闪烁,并且由于屏幕上有多个纹理,因此将过程减慢到可见的程度,但不确定如何更正问题。

1 个答案:

答案 0 :(得分:1)

似乎在渲染功能中,您正在为要加载的每个纹理清除屏幕,因此清除了屏幕,然后加载并渲染了第一个纹理,但是在还渲染第二个纹理之前,将屏幕再次清除,而不是将第二个纹理覆盖在第一个纹理之上,而是在两个纹理之间闪烁