练习贴
c#代码
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class TestInputPosShader : MonoBehaviour
{
public Material material;
const int arrayCount= 2000;
Vector4[] list = new Vector4[arrayCount];
private int tempIndex;
private void Update()
{
if (Input.GetMouseButton(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 1000))
{
// Debug.Log("Raycast hit: " + hit.point);
list[tempIndex]= hit.point;
material.SetVectorArray("_InputPoints", list);
material.SetInt("_InputPointCount", tempIndex+1);
tempIndex++;
if (tempIndex>= arrayCount)
{
tempIndex = 0;
}
}
}
}
}
shader代码
Shader "Custom/MousePointSetColor"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {} //主纹理
_Radius("Radius",float) = 1 //影响半径
_Intensity("Intensity",float) = 1 //影响的强度
_PointColor ("PointColor", Color) = (1,1,1,1) //选中颜色
}
SubShader
{
Tags{"Queue"="Transparent"}
Blend SrcAlpha OneMinusSrcAlpha
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
// make fog work
#pragma multi_compile_fog
#include "UnityCG.cginc"
half _Alpha;
float _Radius;//影响半径
float _Intensity;//影响的强度
uniform int _InputPointCount;
uniform float4 _InputPoints[2000];
float4 _PointColor;
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
fixed3 worldPos : TEXCOORD1;
UNITY_FOG_COORDS(1)
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
float4 _MainTex_ST;
half calculateIntensity(fixed3 worldPos,float4 inputPos,float radius,float intensity)
{
half dis = distance(worldPos,inputPos.xyz);//计算输入点和每个顶点的距离
half ratio = 1-saturate(dis/radius);//saturate 返0~1,计算强度百分比,距离目标点越远影响强度越小
half heat = intensity*ratio;
return heat;
}
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
UNITY_TRANSFER_FOG(o,o.vertex);
float3 worldPos = mul(unity_ObjectToWorld,v.vertex).xyz;//获取每一个顶点信息
o.worldPos = worldPos;
return o;
}
fixed4 frag (v2f i) : SV_Target
{
// sample the texture
fixed4 col = tex2D(_MainTex, i.uv);
// apply fog
UNITY_APPLY_FOG(i.fogCoord, col);
half value = 0;
for( int j = 0 ; j < _InputPointCount;j++ )
{
//计算顶点世界坐标和传入的世界坐标点的影响范围返回值
value+=calculateIntensity(i.worldPos,_InputPoints[j],_Radius,_Intensity);
value=clamp(value,0,1);
}
float rate =1- step(0.01,value);
col= (col*rate)+ (_PointColor*float4(value,value,value,_PointColor.w));
return col;
}
ENDCG
}
}
}
效果图