SFML community forums

Help => System => Topic started by: Glocke on January 26, 2015, 04:29:26 pm

Title: [SOLVED] Multiple conversions between sf::Vector2<T>
Post by: Glocke on January 26, 2015, 04:29:26 pm
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 :)
Title: Re: Multiple conversions between sf::Vector2<T>
Post by: Hapax on January 26, 2015, 06:04:21 pm
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.
Title: Re: Multiple conversions between sf::Vector2<T>
Post by: Laurent on January 26, 2015, 07:07:50 pm
sf::Vector2u target(sf::Vector2i(source) + direction);
Title: Re: Multiple conversions between sf::Vector2<T>
Post by: Glocke on January 26, 2015, 07:44:48 pm
sf::Vector2u target(sf::Vector2i(source) + direction);
Using the ctor was too obvious :o Great ;D Thanks!