游戏开发中的数学和物理算法(3):点之间的距离
1.计算两点之间的距离
公式:a2+b2=c2(勾股定理)
2D:
3D:
计算机实现:
![](https://i-blog.csdnimg.cn/blog_migrate/34031c708bfe702fe82d01ff5c6593aa.gif)
float Distance2D(Point2D p1,Point2D p2)
{
float dx=p1.x-p2.x;
float dy=p1.y-p2.y;
float distance=sqrt(pow(dx,2)+pow(dy,2));
return distance;
}
![](https://i-blog.csdnimg.cn/blog_migrate/34031c708bfe702fe82d01ff5c6593aa.gif)
float Distance3D(Point3D p1,Point3D p2)
{
float dx=p1.x-p2.x;
float dy=p1.y-p2.y;
float dz=p1.z-p2.z;
float distance=sqrt(pow(dx,2)+pow(dy,2)+pow(dz,2));
return distance;
}
2.两点之间的中点
公式:
2D:
3D:
计算机实现:
![](https://i-blog.csdnimg.cn/blog_migrate/34031c708bfe702fe82d01ff5c6593aa.gif)
Point2D MidPoint2D(Point2D p1,Point2D p2)
{
float sx=p1.x+p2.x;
float sy=p1.y+p2.y;
Point2D midPoint;
midPoint.x=sx/2;
midPoint.y=sy/2;
return midPoint;
}