帮我在unity中写一个shader脚本,使用后物体高光闪烁效果,要保证在URP渲染管辖下使用
时间: 2024-03-23 11:36:51 浏览: 126
好的,以下是一个基本的URP高光闪烁shader脚本示例:
```shader
Shader "Custom/URPHighLight" {
Properties {
_Color ("Color", Color) = (1,1,1,1)
_Glossiness ("Smoothness", Range(0,1)) = 0.5
_Metallic ("Metallic", Range(0,1)) = 0.0
_MainTex ("Albedo (RGB)", 2D) = "white" {}
_BumpMap ("Normal Map", 2D) = "bump" {}
_HighLightColor ("HighLight Color", Color) = (1,1,1,1)
_HighLightIntensity ("HighLight Intensity", Range(0,1)) = 0.2
_HighLightSpeed ("HighLight Speed", Range(0,1)) = 0.2
}
SubShader {
Tags { "RenderType"="Opaque" }
LOD 100
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata {
float4 vertex : POSITION;
float3 normal : NORMAL;
float2 uv : TEXCOORD0;
};
struct v2f {
float2 uv : TEXCOORD0;
float3 worldNormal : TEXCOORD1;
float3 worldPos : TEXCOORD2;
UNITY_FOG_COORDS(3)
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
sampler2D _BumpMap;
float4 _Color;
float _Glossiness;
float _Metallic;
float4 _HighLightColor;
float _HighLightIntensity;
float _HighLightSpeed;
v2f vert (appdata v) {
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.worldNormal = UnityObjectToWorldNormal(v.normal);
o.worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
o.uv = v.uv;
UNITY_TRANSFER_FOG(o,o.vertex);
return o;
}
fixed4 frag (v2f i) : SV_Target {
// calculate lighting
float3 worldNormal = normalize(i.worldNormal);
float3 worldPos = i.worldPos;
float3 worldLightDir = normalize(_WorldSpaceLightPos0.xyz - worldPos);
float3 albedo = tex2D(_MainTex, i.uv).rgb * _Color.rgb;
float3 specular = _LightColor0.rgb * _HighLightColor.rgb * _HighLightIntensity;
float3 viewDir = normalize(UnityWorldSpaceViewDir(worldPos));
float3 halfDir = normalize(worldLightDir + viewDir);
float nh = max(0, dot(worldNormal, halfDir));
float spec = pow(nh, 100 * _Glossiness);
float4 c = float4(0,0,0,0);
c.rgb += albedo * _LightColor0.rgb * (nh * _HighLightIntensity + spec * specular);
c.rgb += albedo * _AmbientColor.rgb;
c.a = _Color.a;
return c;
}
ENDCG
}
}
FallBack "Diffuse"
}
```
该shader使用了UnityCG.cginc中的常量和变量,以及URP的一组属性,包括颜色、光滑度、金属度、高光颜色、高光强度和高光速度。在顶点着色器中,我们计算了顶点的世界法线、世界位置和纹理坐标,并通过UNITY_TRANSFER_FOG宏传递了雾效参数。在片段着色器中,我们计算了光照、高光和漫反射,并返回颜色值。
要使用该shader,请将其保存为URPHighLight.shader,然后将其添加到Unity项目中。在材质中,选择该shader并调整属性值以获得所需的高光闪烁效果。
阅读全文