对于我的游戏,我需要在特定时间找出两个物体之间的距离。我的问题只是可以改进 findDistance 函数吗?我似乎没有任何问题,我只是好奇它是否可以做得更好。另外,如果我要在 3D 设置中执行此操作,因为还有另一个轴,我将如何计算它?
#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:
float findDistance(point &x, point &y)
{
float distance, tempx, tempy, tempz;
tempx = (x.x - y.x);
tempx = tempx * tempx; //compiler _might_ be able to make this faster
tempy = (x.y - y.y);
tempy = tempy * tempy;
tempz = (x.z - y.z);
tempz = tempz * tempz;
distance = tempx + tempy + tempz;
distance = sqrt(distance);
return distance;
}
除了将 pos(x,2)
替换为 x*x
之外,这无法优化并保持通用/准确,但如果您不需要通用,它可以更快:
bool distanceLessThan(point &x, point &y, float distance)
{
float tempx, tempy, tempz, tempd;
tempx = std::abs(x.x - y.x);
tempy = std::abs(x.y - y.y);
tempz = std::abs(x.z - y.z);
if (tempx + tempy + tempz < distance) //for small distances, don't square
return true;
if (tempx + tempy + tempz > distance/2) //for large distances, don't square
return false;
tempx = tempx * tempx;
tempy = tempy * tempy;
tempz = tempz * tempz;
tempd = distance * distance;
if (tempx + tempy + tempz < tempd)
return true;
return false;
}
关于c++ - 计算两个物体之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8001924/