今天我们来了解一下怎么使用贴图,把贴图渲染出来
先上代码:
Shader "Unlit/shader9"
{
///鼠标移动正方形
Properties
{
_MainTex("Main Texture",2D)="white"{
}
}
SubShader
{
Tags {
"RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct v2f{
float4 vertex:SV_POSITION;
float4 position:TEXCOORD1;
float2 uv:TEXCOORD;
float4 screenPos:TEXCOORD2;
};
v2f vert(appdata_base v){
v2f o;
o.vertex=UnityObjectToClipPos(v.vertex);
o.position=v.vertex;
o.uv=v.texcoord;
o.screenPos=ComputeScreenPos(o.vertex);
return o;
}
sampler2D _MainTex;
fixed4 frag (v2f i) : SV_Target
{
fixed3 color=tex2D(_MainTex,i.uv).rgb;
return fixed4(color,1.0);
}
ENDCG
}
}
}
其实也就是获取到贴图的颜色信息,再直接输出,此处用到tex2D函数,传入两个参数
sampler2D:贴图信息
uv:UV值 如果uv值为(0,0),则返回左下角的像素,如果uv值为(1,1),则返回右上角的像素,如果uv值为(0.5,0.5),则返回中间像素
在代码中我们剥离了alpha值,只取了rgb三种颜色
如果们需要把图像左右翻转或倒过来,可以通过操作uv的坐标值来实现,如下是左右翻过来
float2 uv=float2(1-i.uv.x,i.uv.y);
fixed3 color=tex2D(_MainTex,uv).rgb;
return fixed4(color,1.0);
上下翻转:
float2 uv=float2(i.uv.x,1-i.uv.y);
fixed3 color=tex2D(_MainTex,uv).rgb;
return fixed4(color,1.0);
旋转90°
Shader "Unlit/shader9"
{
///鼠标移动正方形
Properties
{
_MainTex("Main Texture",2D)="white"{
}
}
SubShader
{
Tags {
"RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct v2f{
float4 vertex:SV_POSITION;
float4 position:TEXCOORD1;
float2 uv:TEXCOORD;
float4 screenPos:TEXCOORD2;
};
v2f vert(appdata_base v){
v2f o;
o.vertex=UnityObjectToClipPos(v.vertex);
o.position=v.vertex;
o.uv=v.texcoord;
o.screenPos=ComputeScreenPos(o.vertex);
return o;
}
float2 rotate(float2 pt,float theta,float aspect){
float c=cos(theta);
float s=sin(theta);
float2x2 mat=float2x2(c,s,-s,c);
pt.y/=aspect;
pt=mul(pt,mat);
pt.y*=aspect;
return pt;
}
sampler2D _MainTex;
fixed4 frag (v2f i) : SV_Target
{
float center=0.5;
float2 uv=rotate(i.uv-center,UNITY_HALF_PI,2.0/1.5)+center;
fixed3 color;
if(uv.x<0||uv.x>1||uv.y<0||uv.y>1){
color=fixed3(0,0,0);
}else{
color=tex2D(_MainTex,uv).rgb;
}
return fixed4(color,1.0);
}
ENDCG
}
}
}
旋转过程中添加了一个rotate函数,该函数主要是通过矩阵实现旋转相应的度数theta,aspect参数主要是处理拉伸的情况。
在旋转之后,会多出相同的画面,这里进行了判断处理,多出的部分变成黑色