一、使用camera.RenderToCubemap(cubemap)生成自定义cubemap
1.搭建场景,天空球等
2.创建适合当前Pos的的Cubemap
Editor
using UnityEngine;
using UnityEditor;
public class RenderCubeMap : ScriptableWizard
{
public Transform renderTrans;
public Cubemap cubemap;
[MenuItem("Tools/CreateCubemap")]
static void CreateCubemap()
{
//"Create Cubemap"是打开的窗口名,"Create"是按钮名,点击时调用OnWizardCreate()方法
ScriptableWizard.DisplayWizard<RenderCubeMap>("Create Cubemap", "Create");//打开向导
}
private void OnWizardUpdate()//打开向导或者在向导中更改了其他内容的时候调用
{
helpString = "选择渲染位置并且确定需要设置的cubemap";
isValid = renderTrans != null && cubemap != null;//isValid为true的时候,“Create”按钮才能点击
}
private void OnWizardCreate()//点击创建按钮时调用
{
GameObject go = new GameObject();
go.transform.position = renderTrans.position;
Camera camera = go.AddComponent<Camera>();
camera.RenderToCubemap(cubemap);//用户提供的Cubemap传递给RenderToCubemap函数,生成六张图片
DestroyImmediate(go);//立即摧毁go
}
}
3.构造Shader和材质
查看代码
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
float3 normal:NORMAL;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
float3 worldPos:TEXCOORD1;
float3 normal:NORMAL;
};
sampler2D _MainTex;
float4 _MainTex_ST;
samplerCUBE _CubeMap;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
o.worldPos = mul(unity_ObjectToWorld,v.vertex);
o.normal = UnityObjectToWorldNormal(v.normal);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
fixed3 V = normalize(i.worldPos - _WorldSpaceCameraPos);
fixed3 N = i.normal;
fixed3 R = reflect(V,N);
//本地CubeMap文件读取
return texCUBE(_CubeMap,R);
//Unity反射探针组件Bake文件读取
fixed4 cubemap = UNITY_SAMPLE_TEXCUBE(unity_SpecCube0,R);
half3 skyColor = DecodeHDR(cubemap,unity_SpecCube0_HDR);
return fixed4(skyColor,1);
}
原理:
效果:
二、使用Unity组件ReflectionProbe生成Cubemap
此方法有限制:只能生成规定空间内物体的Cubemap,并且这些物体必须开启Static
使用此方法的Shader写在上面了,和自定义大区别不大
标签:normal,cubemap,Create,vertex,go,Cubemap From: https://www.cnblogs.com/LateUpdate/p/17968269