首先看一下我们要实现的效果吧:
我第一次看到这个效果时,感觉好厉害,一时间也没什么想法可以去实现,后面仔细去想了下,原来实现的原理还挺简单的(/捂脸)
原理:可以吧球看成一个四维向量的点(CenterPos),然后把CenterPos当成是sin函数的最高点,延伸部分就用sin函数求出顶点的偏移值,就可以出现上述效果啦。
1、设定一个地毯隆起的最大半径(R),也就是A点到CenterPos的长度,A点到CenterPos中间其实是有很多顶点的
2、将每个顶点到CenterPos的距离转化为0-90度,这样我们就可以使用sin函数模拟隆起
3、改变顶点Y的值,调节参数
仔细观察下sin函数的曲线,0-90度是不是很像地毯隆起的部分
重要代码解析:
v2f vert (appdata v)
{
v2f o;
float4 worldPos = mul(unity_ObjectToWorld, v.vertex);//将顶点转到世界坐标下
float2 dir = float2(_CenterPos.x, _CenterPos.z) - float2(worldPos.x, worldPos.z);
float len = sqrt(dot(dir, dir));//求出每个顶点到中心点的距离
if (len < _Radiu)
{
float angle = (_Radiu - len) / _Radiu * 90.0;//将顶点距离转到为0-90度的区间
float rad = (angle * 3.1415926) / 180.0;//角度转弧度,这样才可以使用sin函数
v.vertex.y += sin(rad * _W) * _Height;//根据sin函数偏移,改变顶点位置
}
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
UNITY_TRANSFER_FOG(o,o.vertex);
return o;
}
完整代码:
Shader "YW/RugInteraction"
{
//地毯交互效果
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_CenterPos("中心点",vector) = (0,0,0,0)
_Radiu("半径",Range(0,10)) = 0
_Height("高度",Range(0,10)) = 0
_W("w",Range(0,2)) = 0
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
Cull off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
// make fog work
#pragma multi_compile_fog
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
UNITY_FOG_COORDS(1)
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
float4 _MainTex_ST;
float _Radiu;
float4 _CenterPos;
float _Height;
float _W;
float _Offset;
v2f vert (appdata v)
{
v2f o;
float4 worldPos = mul(unity_ObjectToWorld, v.vertex);
float2 dir = float2(_CenterPos.x, _CenterPos.z) - float2(worldPos.x, worldPos.z);
float len = sqrt(dot(dir, dir));
if (len < _Radiu)
{
float angle = (_Radiu - len) / _Radiu * 90.0;
float rad = (angle * 3.1415926) / 180.0;
v.vertex.y += sin(rad * _W) * _Height;
}
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
UNITY_TRANSFER_FOG(o,o.vertex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
fixed4 col = tex2D(_MainTex,i.uv);
return col;
}
ENDCG
}
}
}
C#代码:
using UnityEngine;
[ExecuteInEditMode]
public class RugInteraction : MonoBehaviour
{
public Material planeMat;
public Transform targetObj;
private Vector4 cubePos = new Vector4(0, 0, 0, 0);
// Update is called once per frame
void Update()
{
cubePos = new Vector4(targetObj.position.x, 0, targetObj.position.z, 0);
planeMat.SetVector("_CenterPos", cubePos);
}
}
由于刚开始学习shader,如有错误请指出,有更好想法的小伙伴欢迎留言