unity5 靜態和動態cubmap


一,靜態cubemap:

asserts窗口 右鍵->Create->Legacy->Cubemap,新建一個cubemap,命名為cubeMap,然后為其各面指定貼圖,如圖:

需要注意的是,unity是左手坐標系,與opengl右手坐標系相反,所以如果我們的六張貼圖是適用於opengl坐標系的,則用到unity中+Z和-Z兩張貼圖要互換。例如下面六個圖是適用於opengl坐標系的(n表示negative,p表示positive):

 

則用到unity中,應:nx添加到-X,ny添加到-Y,nz添加到+Z,px添加到+X,py添加到+Y,pz添加到-Z。

新建shader,命名為cubeMapShader:

Shader "Custom/cubeMapShader" {
	Properties {

		
		
		_MainTex("Base (RGB)",2D) = "white" {}
		_Cubemap("CubeMap",CUBE) = ""{}
		_ReflAmount("Reflection Amount", Range(0.01, 1)) = 1
		_Glossiness ("Smoothness", Range(0,1)) = 0.5
		_Metallic ("Metallic", Range(0,1)) = 0.0
		_Color ("Color", Color) = (0,0,0,1)
	}
	SubShader {
		Tags { "RenderType"="Opaque" }
		LOD 200
		
		CGPROGRAM
		// Physically based Standard lighting model, and enable shadows on all light types
		#pragma surface surf Standard fullforwardshadows

		// Use shader model 3.0 target, to get nicer looking lighting
		#pragma target 3.0

		sampler2D _MainTex;
		samplerCUBE _Cubemap;
		float _ReflAmount;
		half _Glossiness;
		half _Metallic;
		fixed4 _Color;
		
		struct Input {
			float2 uv_MainTex;
			float3 worldRefl;
		};


		void surf (Input IN, inout SurfaceOutputStandard o) {
			// Albedo comes from a texture tinted by color
			fixed4 c = tex2D (_MainTex, IN.uv_MainTex)*_Color;
			o.Albedo = c.rgb;
			// Metallic and smoothness come from slider variables
			o.Metallic = _Metallic;
			o.Smoothness = _Glossiness;
			o.Alpha = c.a;
			o.Emission=texCUBE(_Cubemap, IN.worldRefl).rgb*_ReflAmount;
		}

		ENDCG
	} 
	FallBack "Diffuse"
}

 

新建一個material,命名為cubeMapMat。其shader選Custom/cubeMapShader。shader->Cubemap選前面創建的cubeMap。其余默認。

新建一個球體,命名為sphere1,將其Mesh Renderer->Materials->Element 0 選為cubeMapMat。

則得到一個靜態cubemap球體,如圖:

二,動態cubemap:

創建camera,命名為Camera_cubeMapRealTime,刪除其Audio Listener組件。

新建cubemap,命名為cubeMapRealTime,勾選Readable。

新建material,命名為cubeMapRealTimeMat,其shader選Custom/cubeMapShader。shader->Cubemap選cubeMapRealTime。

創建球體,命名為sphere2。

為sphere2添加腳本cubeMapRealTime.cs:

using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class cubeMapRealTime : MonoBehaviour {

	public Camera camera_cubeMapRealTime;
	public Cubemap cubeMap;
	
	void Start () {
		UpdateCubemap();
	}
	
	void LateUpdate () {
		UpdateCubemap ();
	}
	
	void UpdateCubemap () {
		camera_cubeMapRealTime.transform.position = gameObject.transform.position;
		camera_cubeMapRealTime.RenderToCubemap(cubeMap);
	}
}

Camera_cubeMapRealTime拖給腳本的camera_cubeMapRealTime變量,

cubeMapRealTime拖給腳本的cubeMap變量。

sphere2的Mesh Renderer->Materials->Element 0 選cubeMapRealTimeMat。

此時cubeMapRealTime中產生實時圖像:

運行效果如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM