1
General / Re: How can I make a background repeat infinitely?
« on: January 20, 2023, 04:26:12 am »Here's a little one I made.
Let's say the window and the background texture are 1920x1080.
It uses a single sprite of the background set to 3 times the width of the texture (so it repeats 3 times).
It then snaps the sprite to positions that are multiples of the width (1920). So as the camera pans to the side, the background will ocassionally jump 1920 pixels so it's always filling the window.
It can actually be done with a 2 time repeating texture, but handling -X positions becomes a little trickier, so I just used 3 repeats.
Some code fragments// Make a sprite with the background texture like normal.
// Then set it like this:
tex->setRepeated(true);
sf::Vector2u texSize = tex->getSize();
sprite->setTextureRect(sf::IntRect(sf::Vector2i(0, 0), sf::Vector2i(texSize.x * 3, texSize.y)));
// Later in your rendering code do this:
sf::View view = window.getView();
sf::Vector2f pos = view.getCenter() - view.getSize() * 0.5f; // Find top left corner of the view
pos.x = int(pos.x / texSize.x) * int(texSize.x)-int(texSize.x); // Snap the X coord to multiples of width
sprite->setPosition(pos);
window.draw(*sprite);
Or if I was doing it for myself, I'd probably do a shader version.
I tried doing as you said and it kinda worked! I guess it takes me one step further to getting this resolved but I can't figure it out yet. I tried as you did making use of pointers but the compiler did not take them so I had to declare normal variables for each thing, after that it kind of did the thing, now it does show the image a bit further but its just like stretching the last few pixels of the image. Though it only does it for what would be another additional repetition of the image, after that is just black again, thanks tho! it got me one step closer to where I want to be.