下面代码的运行环境
- Unity : 2022.3.20f1
- Pipeline : URP
步骤思路:①先采样3D场景采样输出成CubeMap文件;
②将CubeMap解出6面图;
③将6面图合并成一张符合球形畸变的全景图;
步骤一:
先采样CubeMap文件,这里必须是6面CubeMap;
采样脚本:
using UnityEngine;
using UnityEditor;
using System.Collections;
public class RenderCubemapWizard : ScriptableWizard
{
public Transform renderFromPosition;
public Cubemap cubemap;
void OnWizardUpdate()
{
string helpString = "Select transform to render from and cubemap to render into";
bool isValid = (renderFromPosition != null) && (cubemap != null);
}
void OnWizardCreate()
{
// create temporary camera for rendering
GameObject go = new GameObject("CubemapCamera");
go.AddComponent<Camera>();
// place it on the object
go.transform.position = renderFromPosition.position;
go.transform.rotation = Quaternion.identity;
// render into cubemap
go.GetComponent<Camera>().RenderToCubemap(cubemap);
// destroy temporary camera
DestroyImmediate(go);
}
[MenuItem("GameObject/Render into Cubemap")]
static void RenderCubemap()
{
ScriptableWizard.DisplayWizard<RenderCubemapWizard>(
"Render cubemap", "Render!");
}
}
步骤二(解出6面图):
using UnityEngine;
using UnityEditor;
using System.IO;
public class CubemapExporter : MonoBehaviour
{
[MenuItem("Assets/Export Cubemap Faces")]
static void ExportCubemapFaces()
{
var cubemap = Selection.activeObject as Cubemap;
if (cubemap == null)
{
Debug.LogError("No cubemap selected.");
return;
}
string path = AssetDatabase.GetAssetPath(cubemap);
string directory = Path.GetDirectoryName(path);
string filename = Path.GetFileNameWithoutExtension(path);
for (int i = 0; i < 6; i++)
{
var faceTexture = new Texture2D(cubemap.width, cubemap.height, TextureFormat.RGB24, false);
var pixels = cubemap.GetPixels((CubemapFace)i);
faceTexture.SetPixels(pixels);
faceTexture.Apply();
byte[] bytes = faceTexture.EncodeToJPG();
File.WriteAllBytes(Path.Combine(directory, $"{filename}_face{(CubemapFace)i}.jpg"), bytes);
Object.DestroyImmediate(faceTexture);
}
Debug.Log("Cubemap faces exported.");
}
}
第三步(合并成全景360°图):
我这里提供一个链接:Cubemap to panorama这一步同样也是可以直接在Unity里面通过shader去合并输出成图,感兴趣的请自行搜索相关教程;
最后预览: