存储SDL渲染器的预定义图层

时间:2016-01-31 17:45:21

标签: c++ sdl

我在这个问题上已经被困了很长时间了: 我的代码看起来像那样

enum class LayerType {Foreground, Terrain, Background, Target};

class Texture
{
private:
    ...
    Texture       * target;
    LayerType       targetLayer;
    ...
public:
    ...
    Texture       & getTarget();
    void            setTarget(Texture & texture);
    ...
};

class Renderer
{
private:
    ...
    map<GAME::LayerType, Texture> layers;
    ...
public:
    ...
    void                drawTexture(Texture & texture);
    ...
};

当调用渲染器的构造函数时,我为每个枚举类型设置了一个条目,因此每个图层都有自己的纹理(并且targetLayer设置为LayerTypeTarget)。我的想法是,我不必以正确的顺序绘制所有纹理,而是使用正确的目标纹理。

渲染器的当前功能如下所示。

void Renderer::present()
{
    this->setRendererEmptyTarget();
    for(map<LayerType, Texture>::reverse_iterator it = this->layers.rbegin(); it != this->layers.rend(); it++)
    {
        this->drawTexture(it->second);
    }
    SDL_RenderPresent(this->ren);
}

和绘图功能如下:

void Renderer::drawTexture(Texture & texture)
{
    if(texture.getTargetLayer() != LayerType::Target)
    {
        this->setRendererTarget(this->layers.find(texture.getTargetLayer())->second);
    }
    SDL_RenderCopy(this->ren, texture.getTexture(), NULL, NULL);
}

问题是所有纹理都是按照函数调用的顺序绘制的,而不是按目标纹理的顺序绘制的。我认为问题可能是缺少对目标纹理的引用。

修改

左图显示了它的样子,右边显示了它的实际外观: http://imgur.com/QafTPuT

左图的代码:

// s1, s2 are surfaces
// the targetTexture contains the sdl flags for a target texture
Texture targetTexture = Texture(this->renderer, LayerType::Target);
Texture t1 = Texture(this->renderer, s1, LayerType::Menu);
Texture t2 = Texture(this->renderer, s2, LayerType::Terrain);

while(running)
{
    this->renderer.setTarget(targetTexture);
    this->renderer.drawTexture(t1);
    this->renderer.setEmptyTarget();
    this->renderer.drawTexture(t2);
    this->renderer.present();
}

正确图像的代码:

// s1, s2 are surfaces
Texture t1 = Texture(this->renderer, s1, LayerType::Menu);
Texture t2 = Texture(this->renderer, s2, LayerType::Terrain);

while(running)
{
    this->renderer.drawTexture(t1);
    this->renderer.drawTexture(t2);
    this->renderer.present();
}

1 个答案:

答案 0 :(得分:0)

我用指针解决了我的问题。我换了

map<GAME::LayerType, Texture> layers;

map<GAME::LayerType, Texture*> layers;

所以,我现在有了参考资料: - )