Skip to content

Instantly share code, notes, and snippets.

@shaggun
Last active October 24, 2023 03:33
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save shaggun/50a9d39187f5516a870aba03528368ee to your computer and use it in GitHub Desktop.
Save shaggun/50a9d39187f5516a870aba03528368ee to your computer and use it in GitHub Desktop.
Bending a mesh with a shader in Unity

Bending a mesh with a shader in Unity

gif

This is a simple shader for Unity to bend a mesh with a sine function. Useful when you want to simulate the bending caused due to a force being applied to an object. The sine function is being plotted along the Z axis, if you want to bend along the X axis edit line 36:

float4 result = (float4(0.0 , ( sin( ( _OffsetSin + ( vertexPos.x * _Frequency ) ) ) * _Amplitude ) , 0.0 , 0.0));

The more vertices your mesh has along the axis you want to bend the smoother it will look. Tested with Unity 2018.2

Shader "BendMesh"
{
Properties
{
_Texture("Texture", 2D) = "white" {}
_Color("Color", Color) = (0,0,0,0)
_Amplitude("Amplitude", Float) = 0
_Frequency("Frequency", Float) = 0
_OffsetSin("OffsetSin", Float) = 0
}
SubShader
{
Tags{ "RenderType" = "Opaque" "Queue" = "Geometry+0" }
Cull Back
CGPROGRAM
#pragma target 3.0
#pragma surface surf Standard keepalpha addshadow fullforwardshadows vertex:vertexDataFunc
struct Input
{
float2 uv_texcoord;
};
uniform sampler2D _Texture;
uniform float4 _Color;
uniform float _OffsetSin;
uniform float _Frequency;
uniform float _Amplitude;
uniform float4 _Texture_ST;
void vertexDataFunc( inout appdata_full v, out Input o )
{
UNITY_INITIALIZE_OUTPUT( Input, o );
float3 vertexPos = v.vertex.xyz;
float4 result = (float4(0.0 , ( sin( ( _OffsetSin + ( vertexPos.z * _Frequency ) ) ) * _Amplitude ) , 0.0 , 0.0));
v.vertex.xyz += result.xyz;
}
void surf( Input i , inout SurfaceOutputStandard o )
{
float2 uv_Texture = i.uv_texcoord * _Texture_ST.xy + _Texture_ST.zw;
o.Albedo = ( tex2D( _Texture, uv_Texture ) * _Color ).rgb;
o.Alpha = 1;
}
ENDCG
}
Fallback "Diffuse"
}
@BaltaKid
Copy link

Do you have the 3DObject?

@shaggun
Copy link
Author

shaggun commented Mar 29, 2021

Do you have the 3DObject?

Yes, it's included in the repo

@condeRod
Copy link

condeRod commented Dec 23, 2022

Hi, what kind of texture work this shader?

Because I'm trying with my textures and I only get a solid color :(
But if I put it in a standard shader it works.

This is my texture
image

Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment