unity5 静态和动态cubmap

一,静态cubemap:

asserts窗口 右键->Create->Legacy->Cubemap,新建一个cubemap,命名为cubeMap,然后为其各面指定贴图,如图:

unity5 静态和动态cubmap

需要注意的是,unity是左手坐标系,与opengl右手坐标系相反,所以如果我们的六张贴图是适用于opengl坐标系的,则用到unity中+Z和-Z两张贴图要互换。例如下面六个图是适用于opengl坐标系的(n表示negative,p表示positive):

unity5 静态和动态cubmap 

则用到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球体,如图:

unity5 静态和动态cubmap

二,动态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中产生实时图像:

unity5 静态和动态cubmap

运行效果如下:

unity5 静态和动态cubmap

你可能感兴趣的:(unity)