Examples!
1) Rounding position. Notice the staircase movement
#include <SFML/Graphics.hpp>
#include <cmath>
int main()
{
sf::View view({0, 0, 128, 128});
sf::RenderWindow window({ 512,512 }, "SFML works!");
window.setFramerateLimit(1);
window.setView(view);
sf::RectangleShape shape({50.f, 50.f});
shape.setFillColor(sf::Color::Green);
sf::Clock clock;
sf::Vector2f pos{32.f, 0.f};
while (window.isOpen())
{
auto dt = clock.restart();
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
pos += { -0.5f, 0.5f };
shape.setPosition({ std::round(pos.x + 0.25f), std::round(pos.y + 0.25f) });
window.clear();
window.draw(shape);
window.display();
}
}
2) Using my overly complicated solution which works fine! So, the only thing I'm hoping is for someone to make it easier.
#include <SFML/Graphics.hpp>
#include <cmath>
float roundCoordinate(float c, float v)
{
float intPart;
if (std::abs(std::modf(c, &intPart)) == 0.5f) {
if (v <= 0.f) {
c = std::ceil(c);
} else {
c = std::floor(c);
}
} else {
c = std::round(c);
}
return c;
}
sf::Vector2f getRoundedPos(const sf::Vector2f& pos, const sf::Vector2f& v)
{
sf::Vector2f roundedPos;
roundedPos.x = roundCoordinate(pos.x, v.x);
roundedPos.y = roundCoordinate(pos.y, v.y);
return roundedPos;
}
int main()
{
sf::View view({0, 0, 64, 64});
sf::RenderWindow window({ 512,512 }, "SFML works!");
window.setFramerateLimit(1);
window.setView(view);
sf::RectangleShape shape({16.f, 16.f});
shape.setFillColor(sf::Color::White);
sf::Clock clock;
sf::Vector2f pos{32.f, 0.f};
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
sf::Vector2f v{ -0.5f, 0.5f };
pos += v;
shape.setPosition(getRoundedPos(pos, v));
window.clear();
window.draw(shape);
window.display();
}
}