Search code examples
3dgeometrymapping2dline

Map triangle and line from 3d to 2d


I have a triangle in 3d and a line, they are lie in one plane. How can I map 5 points from 3d to 2d?

I can convert triangle to 2d, but can't do the same with line.

Vector2[] ConvertTo2d(Vector3 a, Vector3 b, Vector3 c)
{
    var aN = new Vector2(0, 0);
    var bN = new Vector2(0, 0);
    bN.x = Mathf.Sqrt(Mathf.Pow(b.x - a.x, 2f) + Mathf.Pow(b.y - a.y, 2f) + Mathf.Pow(b.z - a.z, 2f));
    var cN = new Vector2(0, 0);
    cN.x = ((b.x - a.x) * (c.x - a.x) + 
            (b.y - a.y) * (c.y - a.y) + 
            (b.z - a.z) * (c.z - a.z)) / bN.x;
    cN.y = Mathf.Sqrt(Mathf.Pow(c.x - a.x, 2f) + Mathf.Pow(c.y - a.y, 2f) + Mathf.Pow(c.z - a.z, 2f) - Mathf.Pow(cN.x, 2f));

    return new[] {aN, bN, cN};
}

Solution

  • Converted it to a code and it works!

    var points = new Vector3[]
    {
        triangleA,
        triangleB,
        triangleC,
        lineStart,
        lineEnd
    };
    
    var pointsIn2D = To2D(points);
    
    Vector2[] To2D(Vector3[] points)
    {
        var A = points[0];
        var B = points[1];
        var C = points[2];
    
        var U = B - A;
        var V = C - A;
        U /= U.magnitude;
        V /= U.magnitude;
    
        var W = Vector3.Cross(U, V);
        U = Vector3.Cross(V, W);
    
        Vector2[] pNew = new Vector2[points.Length];
        for (int i = 0; i < points.Length; i++)
        {
            var P = points[i];
            var xNew = Vector3.Dot(U, P);
            var yNew = Vector3.Dot(V, P);
            pNew[i] = new Vector2(xNew, yNew);
        }
        return pNew;
    }