For my game, I need to find the distance between two objects at certain times. My question is simply can the findDistance function be improved? I don’t seem to have any issues, I’m only curious if it could have been done better. Also, if I were to do this in a 3D setting how would I go about calculating it since there is another axis?
#include <math.h>
#include <iostream>
struct point{float x, y;};
float findDistance(point &x, point &y)
{
float distance, tempx, tempy;
tempx = (x.x - y.x);
tempx = pow(tempx, 2.0f);
tempy = (x.y - y.y);
tempy = pow(tempy, 2.0f);
distance = tempx + tempy;
distance = sqrt(distance);
return distance;
}
int main()
{
point a, b;
a.x = -2;
a.y = -3;
b.x = -4;
b.y = 4;
std::cout << "The distance between point x and y is: " << findDistance(a, b) << std::endl;
return 0;
}
3d:
Other than replacing
pos(x,2)withx*x, this cannot be optimized and remain generic/accurate, but if you don’t need generic, it can be faster: