前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Unity】虚拟相机跟随Player移动并输出jpg图片

【Unity】虚拟相机跟随Player移动并输出jpg图片

作者头像
DevFrank
发布2024-07-24 15:01:54
800
发布2024-07-24 15:01:54
举报
文章被收录于专栏:C++开发学习交流

添加相机输出图片

添加相机,创建GetImage脚本:

思路是创建相机对象,建立事件,按下空格键即将所看到的画面渲染到目标纹理,然后选择保存路径,代码如下:

代码语言:javascript
复制
using UnityEngine;
using System.Collections;
using System.IO;

// 获取副相机图像,空格键截取
public class GetImage : MonoBehaviour
{

    public Camera mainCam; //待截图的目标摄像机
    RenderTexture rt;  //声明一个截图时候用的中间变量 
    Texture2D t2d;  //目标纹理
    int num = 0;  //截图计数

    void Start()
    {
        t2d = new Texture2D(400, 300, TextureFormat.RGB24, false);
        rt = new RenderTexture(400, 300, 24);
        mainCam.targetTexture = rt;
    }

    void Update()
    {
        //按下空格键来截图
        if (Input.GetKeyDown(KeyCode.Space))
        {
            //截图到t2d中
            RenderTexture.active = rt;
            t2d.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
            t2d.Apply();
            RenderTexture.active = null;

            //将图片保存起来
            byte[] byt = t2d.EncodeToJPG(); //转成jpg格式
            File.WriteAllBytes(Application.dataPath + "//" + num.ToString() + ".jpg", byt); //文件写入

            Debug.Log("当前截图序号为:" + num.ToString());
            num++;  //文件序号
        }
    }
}

相机跟随移动

不过,以上相机是固定的,也就只能截图一个位置的图片,我们想要的效果是跟随小车,模拟采集小车相机的画面。

参考这篇,采用固定摄像机方法。

创建 TheThirdPersonCamera脚本并添加到副相机上:

思路是获取Player的位置,然后在此基础上确定相机位置,来实时跟随获取图像,脚本如下:

代码语言:javascript
复制
using UnityEngine;
using System.Collections;

/// <summary>
/// Third person camera.
/// </summary>
public class TheThirdPersonCamera : MonoBehaviour
{
    public float distanceAway = 10f;
    public float distanceUp = 10f;
    public float smooth = 2f;               // how smooth the camera movement is

    private Vector3 m_TargetPosition;       // the position the camera is trying to be in)

    Transform follow;        //the position of Player

    void Start()
    {
        follow = GameObject.FindWithTag("Player").transform;
    }

    void LateUpdate()
    {
        // setting the target position to be the correct offset from the 
        m_TargetPosition = follow.position + Vector3.up * distanceUp + follow.forward * distanceAway;
        //Debug.Log(follow.position);
        //Debug.Log(follow.forward);

        // 相机移动更平滑
        transform.position = Vector3.Lerp(transform.position, m_TargetPosition, Time.deltaTime * smooth);

        // make sure the camera is looking the right way!
        transform.LookAt(follow);
    }
}

最后,截取到的图像如下:

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-07-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 添加相机输出图片
  • 相机跟随移动
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档