Created
July 17, 2016 19:17
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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, ¶llaxShader); | |
window.display(); | |
} | |
return EXIT_SUCCESS; | |
} |
Works perfectly, thanks!
nice! Thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I tried this, FPS didn't change. 1 draw call with 3 parallax background vertexes drops the fps to 45 from +60.