unity中的利用Matrix4x4实现缩放

1、缩放矩阵
unity中的利用Matrix4x4实现缩放_第1张图片

2、示例代码

using UnityEngine;
using System.Collections;

public class MyTransform : MonoBehaviour
{
    public Matrix4x4 matrix;    //平移矩阵
    public Vector4 v;           //临时存储矩阵变换之后的点
    public Vector4 startPos;    //物体初始位置
    public Vector4 startScale;  //物体初始缩放
    public float x = 1;         //x轴平移/缩放
    public float y = 1;         //y轴平移/缩放
    public float z = 1;         //z轴平移/缩放

    /// 
    /// 记录初始位置
    /// 
    private void Start()
    {
        startPos = new Vector4(transform.position.x, transform.position.y, transform.position.z, 1);
        startScale = new Vector4(transform.localScale.x, transform.localScale.y, transform.localScale.z, 1);
    }

    /// 
    /// Update中平移
    /// 
    private void Update()
    {
        //MyTranslate();
        MyScale();
    }

    /// 
    /// 平移函数
    /// 
    private void MyTranslate()
    {
        matrix = Matrix4x4.identity; //单位矩阵
        matrix.m03 = x;
        matrix.m13 = 4;
        matrix.m23 = 5;
        v = matrix * startPos;
        transform.position = new Vector3(v.x, v.y, v.z);
    }

    /// 
    /// 缩放函数
    /// 
    private void MyScale()
    {
        matrix = Matrix4x4.identity;
        matrix.m00 = x;
        matrix.m11 = y;
        matrix.m22 = z;
        v = matrix * startScale;
        transform.localScale = new Vector3(v.x, v.y, v.z);
    }
}

3、将两个脚本放在一个空物体上
unity中的利用Matrix4x4实现缩放_第2张图片

4、拖拽Inspector面板,则可以看到缩放结果:
unity中的利用Matrix4x4实现缩放_第3张图片

你可能感兴趣的:(Unity)