さけのさかなのブログ

同人ゲーム開発やってます。Unity使ったりする。

Unity Matrix4x4で連立方程式を解く

        // 四点を通る三次関数を得る
        static public void CalculateCubicFunctionBy4Points(
            float x1, float y1,
            float x2, float y2,
            float x3, float y3,
            float x4, float y4)
        {
            var matrix = new Matrix4x4();
            matrix[0, 0] = x1 * x1 * x1;
            matrix[0, 1] = x1 * x1;
            matrix[0, 2] = x1;
            matrix[0, 3] = 1f;
            matrix[1, 0] = x2 * x2 * x2;
            matrix[1, 1] = x2 * x2;
            matrix[1, 2] = x2;
            matrix[1, 3] = 1f;
            matrix[2, 0] = x3 * x3 * x3;
            matrix[2, 1] = x3 * x3;
            matrix[2, 2] = x3;
            matrix[2, 3] = 1f;
            matrix[3, 0] = x4 * x4 * x4;
            matrix[3, 1] = x4 * x4;
            matrix[3, 2] = x4;
            matrix[3, 3] = 1f;

            var inversedMatrix = matrix.inverse;

            var rightMatrix = new Vector4(y1, y2, y3, y4);

            var a = Vector4.Dot(inversedMatrix.GetRow(0), rightMatrix);
            var b = Vector4.Dot(inversedMatrix.GetRow(1), rightMatrix);
            var c = Vector4.Dot(inversedMatrix.GetRow(2), rightMatrix);
            var d = Vector4.Dot(inversedMatrix.GetRow(3), rightMatrix);

            // a * x^3 + b * x^2 + c * x + d
        }