Background

Infinite Vertical Scroll

The blank background is boring. A texture that infinitely scrolls may add some color and dynamism to the overall feel of the game, after all, we don't want to fall asleep.

We already know how to render a texture on the screen, we use a sf::Sprite. And we also know how to move it, we can just change the y position of the sprite. But what about the infinite part?

Well, we could make a really big sprite, and hope the player never leaves the game open for more than a few hours. Otherwise, we can be smart about it and we can keep the object still, but move the texture UV mapping, and we already know how to create a quad mesh from the Tilemap!

The background's size needs to cover the whole level, so it will be quite large. An option is to use a texture with the same size as the map, but that is not very flexible for future changes. Instead, we'll enable the repeated property of a texture that, instead of stretching the image, infinitely repeats the same texture and allows UVs to go beyond the usual [0, 1] range.

game/background.h
#pragma once

#include <SFML/Graphics/Texture.hpp>
#include <SFML/Graphics/VertexArray.hpp>
#include <SFML/System/Vector2.hpp>
#include <cstdint>

#include "engine/app.h"

namespace game {

class Background {
 public:
  Background(ng::App* app, sf::Vector2u size);

  void Update();
  void Draw(sf::RenderTarget& target);

 private:
  ng::App* app_ = nullptr;
  sf::Vector2u size_;
  sf::Texture* texture_ = nullptr;
  sf::VertexArray image_vertices_;
  int32_t t_ = 0;
};

}  // namespace game

Last updated