获取平面上最近的点

3

我有一个地形和垂直平面设置,现在我想将这两个意思合并起来,将平面的顶点移动到它们在地形上最近的顶点。

我画了一个图来说明我的想法。最终结果是地形看起来像有一定厚度。

我还需要将点投影到地形上

我在以前的帖子中找到了这段代码:

    float distance = PointToPlaneDistance(smallObj.transform.position, wall.transform.position, wallNormal);

    private float PointToPlaneDistance(Vector3 pointPosition, Vector3 planePosition, Vector3 planeNormal)
    {
        float sb, sn, sd;

        sn = -Vector3.Dot(planeNormal, (pointPosition - planePosition));
        sd = Vector3.Dot(planeNormal, planeNormal);
        sb = sn / sd;

        Vector3 result = pointPosition + sb * planeNormal;
        return Vector3.Distance(pointPosition, result);
    }

the result vector here is the closest point(i think!) But what is the plane normal? Unity has a built in mesh.normals which gives all the surface normals for the terrain. Which one should I use here?

2个回答

5
我希望这可以帮到你:
public static Vector3 ProjectPointOnPlane(Vector3 planeNormal, Vector3 planePoint, Vector3 point){

    float distance;
    Vector3 translationVector;

    //First calculate the distance from the point to the plane:
    distance = SignedDistancePlanePoint(planeNormal, planePoint, point);

    //Reverse the sign of the distance
    distance *= -1;

    //Get a translation vector
    translationVector = SetVectorLength(planeNormal, distance);

    //Translate the point to form a projection
    return point + translationVector;
}



//Get the shortest distance between a point and a plane. The output is signed so it holds information
//as to which side of the plane normal the point is.
public static float SignedDistancePlanePoint(Vector3 planeNormal, Vector3 planePoint, Vector3 point){

    return Vector3.Dot(planeNormal, (point - planePoint));
}



//create a vector of direction "vector" with length "size"
public static Vector3 SetVectorLength(Vector3 vector, float size){

    //normalize the vector
    Vector3 vectorNormalized = Vector3.Normalize(vector);

    //scale the vector
    return vectorNormalized *= size;
}

欲了解更多有用的3D数学知识,请点击此处: https://github.com/GregLukosek/3DMath


抱歉我没能及时回复你。在Unity中,投影点与射线投射的hit.point有什么不同吗?如果有,具体是什么呢? - aditya sarma
我击中的三角形的平面法线是表面法线吗? - aditya sarma

0
Vector3 v_FindPointOnPlaneWithRayCast(Plane i_plane, Vector3 i_target)
{
    Vector3 vectorFind = new Vector3();

    Ray ray = new Ray(i_target, Vector3.forward);
    float enter = 0.0f;
    if (i_plane.Raycast(ray, out enter))
    {
        Vector3 hitPoint = ray.GetPoint(enter);
        vectorFind = hitPoint;
    }
    else
    {
        ray = new Ray(i_target, -Vector3.forward);
        if (i_plane.Raycast(ray, out enter))
        {
            Vector3 hitPoint = ray.GetPoint(enter);
            vectorFind = hitPoint;
        }
    }
    return vectorFind;
}

2
欢迎来到 Stack Overflow。当回答一个已有被接受答案的五年老问题时,非常重要的是要包含解释,并指出你的答案涉及的问题的新方面。 - Jason Aller

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接