usually when i wanted to compute the length of vector, i used traditional way as i have learnt from many tutorials by squared root the dot product of given vector. and these were usually defined in free function for each of them. like so,
//calculates dot product of 2 vectors
inline float dot(const sf::Vector2f& lv, const sf::Vector2f& rv)
{
return lv.x * rv.x + lv.y * rv.y;
}
//Returns length of a given vector
inline float length(const sf::Vector2f& source)
{
return std::sqrt(dot(source, source));
}
//Returns a given vector with its length normalized to 1
inline sf::Vector2f normalise(sf::Vector2f source)
{
float length = std::sqrt(dot(source, source));
if (length != 0) source /= length;
return source;
}
and usage:
auto speed = length(velocity) * dt.asSeconds();
auto amount = normalise(velocity) * speed;
sprite.move(amount );
however, i have found in math.h header file a builtin function hypotf(x,y) that do exactly same thing. later in c++11 defined in cmath by std::hypot(x, y) where x and y is float, which is equivalent to std::fabs(std::complex<float>(x,y)).
typical usage would be some thing like this:
//Returns a given vector with its length normalized to 1
inline sf::Vector2f normalise(sf::Vector2f source)
{
float length = std::hypot(source.x, source.y);
if (length != 0) source /= length;
return source;
}
auto speed = std::hypot(velocity.x, velocity.y) * dt.asSeconds();
auto amount = normalise(velocity) * speed;
sprite.move(amount );
as you can see both did same job while the first is most popular and other rarely used in game dev if not used ever.
my question why most of game dev don't use std::hypot and save them from rewriting those free functions of length and the dot every times, is it because of some performance drawbacks due to std::hypot. or they simply don't know about it.