瓷砖被绘制在错误的位置

Tiles being drawn in the wrong location

我终于设法以某种正确的方式在屏幕上绘制了我的图块。虽然位置有点偏,我也想不通为什么...

我正在使用 SFML 绘图。

Tile.hpp:

#ifndef TILE_HPP
#define TILE_HPP

#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>

#include "textureManager.hpp"

class Tile {
public:
    Tile();
    Tile(sf::Vector2i coord, int biome);
    ~Tile();

    sf::Vector2i getCoord() const { return coord; };
    int getBiome() const { return biome; };

    void setCoord(sf::Vector2i coord) { this->coord = coord; };
    void setBiome(int biome) { this->biome = biome; };

    void draw(int x, int y, sf::RenderWindow* rw);
    void update(sf::Texture& texture);

private:
    sf::Vector2i coord;
    int biome;

    sf::Sprite sprite;
};

#endif

Tile.cpp

#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>

#include "textureManager.hpp"
#include "tile.hpp"

Tile::Tile()
{}

Tile::Tile(sf::Vector2i coord, int biome) {
    this->biome = biome;
    this->coord = coord;
}

Tile::~Tile(){}

void Tile::draw(int x, int y, sf::RenderWindow* rw)
{
    sprite.setPosition(x, y);
    rw->draw(sprite);
}

void Tile::update(sf::Texture& texture)
{
    switch (biome)
    {
        // Not important here
    }
}

现在是更相关的部分:绘图

void StatePlay::draw(const float dt)
{
    game->window.setView(view);
    game->window.clear(sf::Color::Black);

    sf::Vector2f offset = camera.getLocation();
    int newX = (offset.x / map.getTileSize()) - (map.chunkSize / 2);
    int newY = (offset.y / map.getTileSize()) - (map.chunkSize / 2);

    for (int x = 0; x < map.chunkSize; x++)
    {
        for (int y = 0; y < map.chunkSize; y++)
            {
                Tile tile = map.getTile(newX + x, newY + y);
                tile.draw((newX + x) * map.getTileSize(), (newY + y) * map.getTileSize(), &game->window);
            }
        }

    return;
}

StatePlay::StatePlay(Game* game)
{
    this->game = game;
    sf::Vector2f pos = sf::Vector2f(game->window.getSize()); // 1366x768
    view.setSize(pos);
    pos *= 0.5f; // 688x384
    view.setCenter(pos);

    // Initialize map
    map.init(game->gameTime, game->textureManager.getImage("tileset.png"));

    float w     = (float) map.getWidth(); // 500
    float h     = (float) map.getHeight(); // 500
    w           *= 0.5f; // 250
    h           *= 0.5f; // 250
    w           *= map.getTileSize(); // 250 * 32 = 8000
    h           *= map.getTileSize(); // 250 * 32 = 8000
    // Move camera
    // Uses view::move from sfml to move the view with w and h
    // Also sets camera private to w and h values, return with camera::getLocation()
    camera.setLocation(&view, sf::Vector2f(w, h));
}

结果是我只看到屏幕左下角的 ~10 个方块,覆盖了大约 3/4。

选择了正确的图块,但绘制位置错误...它应该在屏幕上尽可能多地绘制 64x64(每个 x 32px)图块的中心。

我已经解决了这个问题。这是一个非常愚蠢的错误...

起初不绘制任何东西,将视图居中放置在 0.5f * sf::View::getSize() 上是正常的,以便使视图居中放置在您的 window 上。所以中心已经是我 window 大小的一半。使用 Camera::setLocation() 时,我使用 sf::View::move() 相应地移动视图。因此,当试图将其置于地图中心时,它正确地添加了 x 和 y,但也是我 window 大小的一半。这导致偏移量不正确。减去或省略这些值已经解决了这个愚蠢的问题。

感谢您的帮助。