Skip to content

Instantly share code, notes, and snippets.

@MarioLiebisch
Created July 17, 2016 19:17
Show Gist options
  • Save MarioLiebisch/c965e4caf4360ebd6def549d60423740 to your computer and use it in GitHub Desktop.
Save MarioLiebisch/c965e4caf4360ebd6def549d60423740 to your computer and use it in GitHub Desktop.
SFML Example to render a repeated parallax background using a vertex shader for movement.
#include <SFML/Graphics.hpp>
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 600), "Parallax Example",
sf::Style::Titlebar | sf::Style::Close);
window.setVerticalSyncEnabled(true);
sf::Texture texture;
if (!texture.loadFromFile("resources/background.jpg"))
return EXIT_FAILURE;
texture.setRepeated(true);
sf::Sprite sprite(texture);
sprite.setPosition(0, 0);
sprite.setColor(sf::Color(255, 255, 255, 200));
sf::Shader parallaxShader;
parallaxShader.loadFromMemory(
"uniform float offset;"
"void main() {"
" gl_Position = gl_ProjectionMatrix * gl_ModelViewMatrix * gl_Vertex;"
" gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;"
" gl_TexCoord[0].x = gl_TexCoord[0].x + offset;" // magic
" gl_FrontColor = gl_Color;"
"}"
, sf::Shader::Vertex);
float offset = 0.f;
sf::Clock clock;
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
switch (event.type) {
case sf::Event::Closed:
window.close();
break;
}
}
// I set an arbitrary value as the offset, you'd calculate this based on camera position
parallaxShader.setUniform("offset", offset += clock.restart().asSeconds() / 10);
window.clear();
window.draw(sprite, &parallaxShader);
window.display();
}
return EXIT_SUCCESS;
}
@ekaktusz
Copy link

ekaktusz commented May 4, 2022

Works perfectly, thanks!

@Ttunay
Copy link

Ttunay commented Mar 22, 2024

nice! Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment