zl程序教程

您现在的位置是:首页 >  其它

当前栏目

unity用虚拟相机截图2

Unity 虚拟 截图 相机
2023-09-27 14:25:49 时间

unity用虚拟相机截图_天人合一peng的博客-CSDN博客

动态的修改物体的位姿,并截图保存

 

MainLogic.cs

using System.IO;
using UnityEngine;

public class MainLogic : MonoBehaviour
{
    public int _DataCount = 2000;
    public Transform _Model;
    public float _minScale = 1f;
    public float _maxScale = 2f;

    private int _DataIndex = 0;
    private string _outputDir;


    // Start is called before the first frame update
    void Start()
    {
        string outputRoot = Application.dataPath + "/../" + "output";
        if (!Directory.Exists(outputRoot)) Directory.CreateDirectory(outputRoot);
        string currentTime = System.DateTime.Now.ToString("yyyy.MM.dd HH.mm.ss");
        _outputDir = outputRoot + "/" + currentTime;
        if (!Directory.Exists(_outputDir)) Directory.CreateDirectory(_outputDir);
    }

    // Update is called once per frame
    void Update()
    {
        if (_DataIndex == 0)
        {
            // Skip the first frame.
            _DataIndex++;
            return;
        }

        if (_DataIndex <= _DataCount)
        {
            // 1 动态变化修改物体的旋转角度
            float rotationX = Random.Range(0f, 360f);
            float rotationY = Random.Range(0f, 360f);
            float rotationZ = Random.Range(0f, 360f);
            _Model.eulerAngles = new Vector3(rotationX, rotationY, rotationZ);


            // 2 动态变化修改物体的position
            float positionX = Random.Range(-0.5f, 0.5f);
            float positionY = Random.Range(-0.5f, 0.5f);
            float positionZ = Random.Range(-0.5f, 0.5f);
            _Model.transform.position = new Vector3(positionX, positionY, positionZ);

            // 3 动态变化修改物体的缩放比例
            float scale = Random.Range(_minScale, _maxScale);
            _Model.localScale = new Vector3(scale, scale, scale);

            Debug.Log("Rotation: " + rotationX + "," + rotationY + "," + rotationZ + "; Scale: " + scale);

            string screenshotFile = _outputDir + "/" + _DataIndex + ".png";
            ScreenCapture.CaptureScreenshot(screenshotFile);


            Matrix4x4 mat = Matrix4x4.TRS(_Model.position, _Model.rotation, _Model.localScale);
            string pose = mat.m00.ToString() + " " + mat.m01.ToString() + " " + mat.m02.ToString() + " " + mat.m03.ToString() + "\n"
                + mat.m10.ToString() + " " + mat.m11.ToString() + " " + mat.m12.ToString() + " " + mat.m13.ToString() + "\n"
                + mat.m20.ToString() + " " + mat.m21.ToString() + " " + mat.m22.ToString() + " " + mat.m23.ToString() + "\n"
                + mat.m30.ToString() + " " + mat.m31.ToString() + " " + mat.m32.ToString() + " " + mat.m33.ToString();
            string poseFile = _outputDir + "/" + _DataIndex + ".txt";
            File.WriteAllText(poseFile, pose);

            _DataIndex++;
        }
        else
        {
            Application.Quit();
        }
    }
}

程序运行时在Scene窗口动态变化可以看见。

 结果

 

txt中保存的是物体的6自由度信息