c++ - 计算两个物体之间的距离

标签 c++ math distance

对于我的游戏,我需要在特定时间找出两个物体之间的距离。我的问题只是可以改进 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/

相关文章:

Android:计算两个位置之间距离的最佳方法

c++ - 如何在 x64 Visual C++ 中执行裸函数和内联汇编程序

c++ - getch() 的奇怪行为

mysql - 确定 n 维中点之间的距离

java - 给定 Integer n 和 Double x。计算 : sin x + sinsin x +. ..+sinsin...sinx。其中n——罪的数目

java - 如何快速找到给出最大值的点?请使用 Java 或 C++ 代码

c++ - 查找表示 GPS 路线的两条线之间的距离(MATLAB、Java、C++ 或 Python)

c# - RegAsm.exe 和 regsvr32 有什么区别?如何使用 regsvr32 生成 tlb 文件?

c++ - std::map 和 _CrtIsValidHeapPointer 错误

c++ - 优雅地上下数