#include "Zone.hpp"
#include "Debug.h"
Zone::Zone(State::Context con, ZoneData ld)
:context{con}
{
textures.load("LevelSheet", ld.getSheet());
textures.load("Player", "img/player.png");
textures.get("LevelSheet").setSmooth(false);
bounds = sf::IntRect{0, 0, ld.getWidth(), ld.getHeight()};
sf::Vector2u tileSheetSize = textures.get("LevelSheet").getSize();
int tileSize = ld.getTileSize();
int maxTilesInRow = tileSheetSize.x / tileSize;
map2Layer(ld.getMap(), bgLayer, tileSize, maxTilesInRow);
map2Layer(ld.getCollidables(), collidablesLayer, tileSize, maxTilesInRow);
player.setTexture(textures.get("Player"), {0,0,tileSize, tileSize});
player.setPosition(ld.getSpawnPosition().x, ld.getSpawnPosition().y);
drawOffset = tileSize * 30;
worldView.zoom(.5);
worldView.setSize(context.window->getSize().x/2, context.window->getSize().y/2);
worldView.setCenter(player.getPosition());
}
void Zone::update(sf::Time deltaT)
{
player.handleInput(bounds);
}
void Zone::draw()
{
worldView.setCenter(player.getPosition());
context.window->setView(worldView);
for (auto &tile : bgLayer)
if (isInBounds(tile))
context.window->draw(tile);
for (auto obj : collidablesLayer)
if (isInBounds(obj))
context.window->draw(obj);
context.window->draw(player);
}
void Zone::handleEvent(const sf::Event& event)
{
}
bool Zone::isInBounds(sf::Sprite& tile)
{
//TILE LEFT X IS > WORLD LEFT X (WORLD CENTER X - HALF WORLD WIDTH)
bool inLeft = tile.getPosition().x >= worldView.getCenter().x - (worldView.getSize().x/2 + drawOffset);
//TILE LEFT X IS < WORLD RIGHT X (WORLD CENTER X + HALF WORLD WIDTH)
bool inRight = tile.getPosition().x <= worldView.getCenter().x + (worldView.getSize().x/2 + drawOffset);
//TILE TOP Y > WORLD TOP Y (WORLD CENTER Y - HALF WORLD HEIGHT)
bool inTop = tile.getPosition().y >= worldView.getCenter().y - (worldView.getSize().y/2 + drawOffset);
//TILE BOTTOM Y < WORLD BOTTOM Y (WORLD CENTER Y + HALF WORLD HEIGHT)
bool inBottom = tile.getPosition().y <= worldView.getCenter().y + (worldView.getSize().y/2 + drawOffset);
if (inLeft && inRight && inTop && inBottom)
return true;
return false;
}
void Zone::map2Layer(const std::vector<std::vector<int>> &source, std::vector<sf::Sprite> &destination, int tileSize, int rowMax)
{
for (int i = 0; i < source.size(); i++)
for (int j = 0; j < source[i].size(); j++)
if (source[i][j] >= 0)
{
sf::Vector2i tilePosition = {source[i][j] * tileSize, (source[i][j] * tileSize) % rowMax};
sf::Sprite tile{textures.get("LevelSheet"), {tilePosition, {tileSize, tileSize}}};
tile.setPosition({j * tileSize * 1.f, i * tileSize * 1.f});
destination.push_back(tile);
}
}