官方論壇上面老外討論的解答
生成CubeMap使用的是Camera內(nèi)置的接口 Camera.RenderToCubemap
docs
using UnityEditor;
using UnityEngine;
public class CubeMapMaker : ScriptableWizard
{
public Transform renderFromPosition=null;
public Cubemap cubemap=null;
void OnWizardUpdate()
{
//選擇一個(gè)gameObject用于確定渲染起始位置,同時(shí)選擇一個(gè)cubemap用于渲染
helpString = "Select transform to render from and cubemap to render into";
bool isValid = (renderFromPosition != null) && (cubemap != null);
}
void OnWizardCreate()
{
//創(chuàng)建用于渲染的臨時(shí)相機(jī)
GameObject gameObject = new GameObject("CubemapCamera");
gameObject.AddComponent<Camera>();
//將臨時(shí)相機(jī)綁到目標(biāo)物體上
gameObject.transform.position = renderFromPosition.position;
gameObject.transform.rotation = Quaternion.identity;
//渲染為cubemap
gameObject.GetComponent<Camera>().RenderToCubemap(cubemap);
//刪除臨時(shí)相機(jī)
DestroyImmediate(gameObject);
}
[MenuItem("GameObject/Render2Cubemap")]
static void Render2Cubemap()
{
ScriptableWizard.DisplayWizard<CubeMapMaker>(
"Render Cubemap", "Render"
);
}
}
導(dǎo)出Cuebmap是通過(guò)讀取CubemapFace然后用Texture2D的功能導(dǎo)出為圖片绞铃,但是由于一些問(wèn)題镜雨,導(dǎo)出圖片之前要先將Texture2D垂直和水平翻轉(zhuǎn)
using UnityEngine;
using UnityEditor;
using System.Linq;
using System.IO;
public class SaveCubeMap2Png : ScriptableWizard
{
public Cubemap cubemap = null;
[MenuItem("GameObject/SaveCubeMap2Png")]
private static void MenuEntryCall()
{
ScriptableWizard.DisplayWizard<SaveCubeMap2Png>("SaveCubeMap2Png", "Save");
}
public static void FlipPixels(Texture2D texture, bool flipX, bool flipY)
{
Color32[] originalPixels = texture.GetPixels32();
var flippedPixels = Enumerable.Range(0, texture.width * texture.height).Select(index =>
{
int x = index % texture.width;
int y = index / texture.width;
if (flipX)
x = texture.width - 1 - x;
if (flipY)
y = texture.height - 1 - y;
return originalPixels[y * texture.width + x];
}
);
texture.SetPixels32(flippedPixels.ToArray());
texture.Apply();
}
private void OnWizardCreate()
{
int width = cubemap.width;
int height = cubemap.height;
Texture2D texture2D = new Texture2D(width, height, TextureFormat.RGB24, false);
for (int i = 0; i < 6; i++)
{
texture2D.SetPixels(cubemap.GetPixels((CubemapFace)i));
//翻轉(zhuǎn)像素,由于某種原因儿捧,導(dǎo)出的圖片需要進(jìn)行翻轉(zhuǎn)
FlipPixels(texture2D, true, true);
//此處導(dǎo)出為png
File.WriteAllBytes(Application.dataPath + "/" + cubemap.name + "_" + ((CubemapFace)i).ToString() + ".png", texture2D.EncodeToPNG());
}
DestroyImmediate(texture2D);
}
private void OnWizardUpdate()
{
helpString = "Select cubemap to save to individual .png";
if (Selection.activeObject is Cubemap && cubemap == null)
cubemap = Selection.activeObject as Cubemap;
isValid = (cubemap != null);
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者