用世界矩阵变换局部坐标,得到世界坐标

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wodownload2/article/details/85008782

例子如下:
[email protected]:yichichunshui/LocalToWorldMatrix.git

在这里插入图片描述
立方的坐标:
在这里插入图片描述

立方体的子节点球体坐标为:
在这里插入图片描述

测试程序:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
    public Transform m_sphere;  //立方体下的球体
	void Start ()
    {
        Matrix4x4 localM = this.transform.worldToLocalMatrix; //局部矩阵
        Matrix4x4 worldM = this.transform.localToWorldMatrix; //世界矩阵
        PrintMatix(localM); //打印局部矩阵
        PrintLine();        //打印分割符号
        PrintMatix(worldM); //打印世界矩阵

        //得到局部坐标的四位向量
        //用世界矩阵乘以局部坐标,得到世界坐标
        Vector4 sphereWorldPos = worldM * GetVector4(m_sphere.transform.localPosition);
        print(sphereWorldPos);
    }

    public Vector4 GetVector4(Vector3 v3)
    {
        return new Vector4(v3.x, v3.y, v3.z, 1);
    }

    private void PrintLine()
    {
        Debug.Log("==============================");
    }

    private void PrintVector4(Vector4 v)
    {
        Debug.Log(v.x + "   " + v.y + "  " + v.z + "   " + v.w);
    }

    private void PrintMatix(Matrix4x4 m)
    {
        Debug.Log(m.m00 + "  " + m.m01 + "  " + m.m02 + "  " + m.m03);
        Debug.Log(m.m10 + "  " + m.m11 + "  " + m.m12 + "  " + m.m13);
        Debug.Log(m.m20 + "  " + m.m21 + "  " + m.m22 + "  " + m.m23);
        Debug.Log(m.m30 + "  " + m.m31 + "  " + m.m32 + "  " + m.m33);
    }
}

在这里插入图片描述
可以看到球体的世界坐标为确实是(1,0,0)。

猜你喜欢

转载自blog.csdn.net/wodownload2/article/details/85008782