Hi, I'm building a grid-based game with discrete movement. So I use sf::Vector2u as grid coordinates - because they're always positive - and sf::Vector2i to express "normalized" movement directions. Of course they're not normalized in the typical sense of vectors but each component is either -1, 0 or +1, which makes it easy to calculate movement targets.
My "problem" is that calculating such targets implies some typecasting and I'm not sure what's the "best" way to do it:
1st approach:
sf::Vector2u target = static_cast<sf::Vector2u>(static_cast<sf::Vector2i>(source) + direction);
This makes use of two explicit conversions (per component) which is .. very explicit ^^ .. but not really beautiful from my point of view.
2nd approach:
sf::Vector2u target;
target.x = static_cast<unsigned int>(target.x + direction.x);
target.y = static_cast<unsigned int>(target.y + direction.y);
This uses two explicit conversion and two implicit (unsigned int + int), which isn't that explicit anymore :S
Other approaches might be overloading operator+ / operator+= which I'd like to avoid, because it might cause errors when using the + operator without absolute care referring to the used types in the expression.
Another solution might be a free function such as sf::Vector2u applyDirection(sf::Vector2u const &, sf::Vector2i const &). But I'm not quite sure how to implement it (or the operator overload) correctly: using the explicit approach (1st) or the semi-explicit approach (2nd) or a different way?
Kind regards
Glocke :)
You could use the vector2's constructor to convert it for you thus:
sf::Vector2u target = sf::Vector2u(sf::Vector2i(source) + direction);
which improves readability on method 1.
sf::Vector2u target(sf::Vector2i(source) + direction);
sf::Vector2u target(sf::Vector2i(source) + direction);
Using the ctor was too obvious :o Great ;D Thanks!