Is there a way to draw a background sprite over and over? Or to add a background sprite on top of each other?

Viewed 39

So I am trying to make a platform that is based on JumpKing and I want to use my sprite image and make it so that it repeats it over and over vertically. Is there a way to make it loop or can you add a sprite background on top of each other.

Background::Background()
{
    background.setTexture(Images::getImage(BACKGROUND));
}

void Background::draw(sf::RenderTarget &window, sf::RenderStates states) const
{
    if(!getStates(HIDDEN)){
        window.draw(background);
    }
}

void Background::setScale(float x, float y)
{
    background.setScale(x, y);
}

This is the code that where I am drawing the background, it is taking the getImage that is from the images.cpp. The getStates is saying that if the getState is hidden then it won't draw the background.

std::map<ImageName, sf::Texture> Images::images;
std::string Images::getImagePath(ImageName name)
{
    switch(name){
        case JUMP_KING: return "Images/Megaman.png";
        case BACKGROUND: return "Images/sky background.png";
        case PLATFORM: return "Images/platforms.png";
    }
    return std::string();
}

void Images::loadImage(ImageName name)
{
    images[name].loadFromFile(getImagePath(name));
}

sf::Texture &Images::getImage(ImageName name)
{
    loadImage(name);
    return images[name];
}

This Images.cpp is there it loads the images in my folder for my game

States::States()
{
    for(int i=0; i<LAST_STATE; i++){
        states[StatesEnum(i)] = false;
    }
}

bool States::getStates(StatesEnum state) const
{
    return states.at(state);
}

void States::disableState(StatesEnum state)
{
    states[state] = false;
}

void States::enableState(StatesEnum state)
{
    states[state] = true;
}

void States::toggleState(StatesEnum state)
{
    states[state] = !states[state];
}
enum StatesEnum{
    WARP,
    WARP_HORIZONTAL,
    WARP_VERTICAL,
    FORWARD,
    BACKWARD,
    HIDDEN,
    JUMP,
    GOING_UP,
    LAST_STATE
}

This is my state enum which goes to the states.cpp so that the these states can be used. This is how my background.cpp is using that

1 Answers

I want to use my sprite image and make it so that it repeats it over and over vertically

You should load textures and not images, for what you want.

  • Images are an abstraction to store arrays of pixels.
  • Textures are images stored in the graphics card for drawing.

So to manipulate the properties of your image, related to how they are drawn, load them as sf::Texture and not as sf::Image.

That being said, you can use sf:Texture::setRepeated to make the texture repeat, before you set it as the texture of your sf::Sprite (which I assume you are using as your Background::background).

I strongly recommend you reading the complete SFML docs, specially the tutorial on this topic.

Related