获取相机内容,实现分屏效果
场景搭建:
1、场景中包括2个相机:main Camera 作为主相机拍摄游戏画面。再创建一个相机camera用于拍摄另一个屏幕内容,background的Alpha通道值设为0,保证背景透明。
2、创建一个quad作为画面显示面板。创建一个cube作为camera显示内容。
3、创建一个C#脚本FogOfWarRenderTex.cs。用于将camera渲染的画面显示到quad的shader中_MainTex1上。代码如下:
using UnityEngine;
using System.Collections;
//[ExecuteInEditMode]
//[RequireComponent (typeof(Camera))]
public class FogOfWarRenderTex : MonoBehaviour
{
RenderTexture renderTex; //该相机渲染出的纹理
Camera camera; //渲染用的相机
GameObject quad; //渲染到指定面片上
GameObject cube; //需要被渲染的对象
// Use this for initialization
void Start()
{
renderTex = new RenderTexture(200, 200, 16, RenderTextureFormat.Default); //创建一个新的RenderTexture
cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = new Vector3(0, 0, 1);
cube.layer = 31;
quad = GameObject.CreatePrimitive(PrimitiveType.Quad);
quad.transform.position = new Vector3(2, 0, 2);
quad.name = "quad";
camera = new GameObject("NPCCamera").AddComponent<Camera>();
camera.targetTexture = renderTex; //相机的目标纹理赋值
camera.transform.position = new Vector3(0, 0, 0);
camera.clearFlags = CameraClearFlags.Color;
camera.backgroundColor =new Color(0,0,0,0);
camera.cullingMask = 1<<31;
camera.orthographic = true;
camera.orthographicSize = 1;
camera.nearClipPlane = 0.3f;
camera.farClipPlane = 10f;
//Shader.SetGlobalTexture("_MainTex1", camera.targetTexture); //给全局shader中的纹理_MainTex1赋值,所有使用该shader的物体都会显示相机渲染的画面
quad.GetComponent<MeshRenderer>().material = new Material(Shader.Find("LT/NPC_UI"));
quad.GetComponent<MeshRenderer>().sharedMaterial.mainTexture = renderTex;
quad.GetComponent<MeshRenderer>().sharedMaterial.SetColor("_MainColor",Color.white) ;
//GameObject obj = Instantiate(quad, new Vector3(0, 0, 0),Quaternion.identity) as GameObject;
}
}
创建一个简单的透明的包含_MainTex1属性的shader(该属性可不显示到Properties),将此shader指定到plane。
Shader "LT/Unlit2"
{
Properties
{
_MainColor ("MainColor", COLOR) = (0.5,0.5,0.5,1.0)
// _MainTex1("Main Texture",2D) = "while" {} //该属性可不显示到Properties
}
SubShader
{
Tags{"Queue" = "Transparent" "RnderType" = "Transparent" "IgnorProjection" = "true"}
Pass
{
ZWrite off
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
fixed4 _MainColor;
sampler2D _MainTex1;
float4 _MainTex1_ST;
float _Red;
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
v2f vert (appdata v)
{
v2f o;
o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
o.uv = TRANSFORM_TEX(v.uv,_MainTex1);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
// sample the texture
fixed4 col =tex2D(_MainTex1,i.uv)* _MainColor;
return col;
}
ENDCG
}
}
}