Nice! I wasn't aware of the std::hypot() function.
As fastcall22 mentioned, you actually don't need to do a squareroot, unless you actually want the actual distance. If you just want to check if something is within range, then you do:
((x2-x1)^2 + (y2-y1)^2) < (distance^2) // '^2' means to square it.
Basically, the same as Pygorean's theorum, but instead of square-rooting the result, you square the distance, which is faster if you're going to be doing it alot - for example, if you need to test which entities are within range of other entities or within range of the player, but don't need to know the actual distance, only if it is within range or not.
Probably a pre-mature optimization, but if you're going to wrap it in a convenience function, you might as well write both versions.
[rollup=C++ code]
//Returns true if we are within 'distance' of 'other'. This is faster than 'DistanceFrom', because it saves a sqrt().
bool cPoint::WithinDistanceOf(const cPoint &other, int distance) const
{
//Pygorean's theorum: A^2 + B^2 = C^2
int horizontal = (this->x - other.x); //(this->x - other.x) could be negative, but multiplying it by itself will always be positive anyway.
horizontal *= horizontal;
int vertical = (this->y - other.y);
vertical *= vertical;
//Square the distance.
distance *= distance;
//Use the squared distance for comparison, instead of getting the square root.
return (horizontal + vertical) <= distance;
}
//Returns the absolute distance between this point and 'other'.
int cPoint::DistanceFrom(const cPoint &other)
{
//Pygorean's theorum: A^2 + B^2 = C^2
int horizontal = (this->x - other.x); //(this->x - other.x) could be negative, but multiplying it by itself will always be positive anyway.
horizontal *= horizontal;
int vertical = (this->y - other.y);
vertical *= vertical;
return std::sqrt(horizontal + vertical);
}
[/rollup]