Skip to content

Instantly share code, notes, and snippets.

@azihassan
Created December 31, 2016 23:22
Show Gist options
  • Save azihassan/e129d0c2255e57bf6af2c0d7aad1d514 to your computer and use it in GitHub Desktop.
Save azihassan/e129d0c2255e57bf6af2c0d7aad1d514 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
#include <SFML/Graphics.hpp>
class Scroller
{
sf::Texture texture;
sf::IntRect rect;
public:
Scroller(sf::Texture& texture)
{
this->texture = texture;
texture.setRepeated(true);
this->texture.setRepeated(true);
rect = sf::IntRect(0, 0, 800, 480);
}
void scrollLeft(float pixels)
{
rect.left -= pixels;
}
void scrollRight(float pixels)
{
rect.left += pixels;
}
sf::Sprite getSprite()
{
sf::Sprite sprite;
sprite.setTexture(texture);
sprite.setTextureRect(rect);
return sprite;
}
};
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 480), "Parallax");
sf::Texture sky;
sky.loadFromFile("layers\\Sky_back_layer.png");
sf::Texture vegetation;
vegetation.loadFromFile("layers\\Vegetation_middle_layer.png");
sf::Texture ground;
ground.setRepeated(true);
ground.loadFromFile("layers\\Ground_front_layer.png");
std::cout << ground.getSize().x << ':' << ground.getSize().y << std::endl;
std::vector<Scroller> scrollers {
Scroller(ground),
Scroller(vegetation)
};
int speed = 2;
while(window.isOpen())
{
sf::Event event;
while(window.pollEvent(event))
{
if(event.type == sf::Event::Closed)
{
window.close();
break;
}
}
window.clear();
for(size_t i = 0; i < scrollers.size(); i++)
{
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
scrollers[i].scrollRight(speed * (i + 1));
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
scrollers[i].scrollLeft(speed * (i + 1));
window.draw(scrollers[i].getSprite());
}
window.display();
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment