Unity3D计算点到线段的最短距离
程序员文章站
2022-04-01 15:51:10
...
float distanceFromSegment(Vector3 v1, Vector3 v2, Vector3 point){
float xDis = v2.x-v1.x;
float yDis = v2.y-v1.y;
float zDis = v2.z-v1.z;
float dx = point.x-v1.x;
float dy = point.y-v1.y;
float dz = point.z-v1.z;
float d = xDis*xDis+yDis*yDis+zDis*zDis;
float t = xDis*dx+yDis*dy+zDis*dz;//向量点积
if(d>0){
t/=d;
}
if(t<0){
t=0;
}else if(t>1){
t=1;
}
dx = v1.x+t*xDis-point.x;
dy = v1.y+t*yDis-point.y;
dz = v1.z+t*zDis-point.z;
return Mathf.Sqrt(dx*dx+dy*dy+dz*dz);
}