Skip to main content

Curved Surface Shader [ Unity Implementation ]

Curved Surface Shader
This is the shader that we will be having at the end of this tutorial.
Endless Runner Example
Gravity Visualizer
 The curved surface shader is capable of achieving really varied visual effects from showing space-time curve due to gravity to a generic curved world shader that is seen in endless runners like Subway Surfers.
The concepts that you learn here can open you up to a new way of looking at shaders and if you didn't think they were the coolest thing ever already, hopefully let this be the turning point.😝.

Both the examples show above use the same exact material is just that different values have been passed to the shader.
Start by creating a new unlit shader in Unity and we will work our way from there.
First we define what the properties are:
_MainTex("Texture", 2D) = "white" {}
_BendAmount("Bend Amount", Vector) = (1,1,1,1)
_BendOrigin("Bend Origin", Vector) = (0,0,0,0)
_BendFallOff("Bend Falloff", float) = 1.0
_BendFallOffStr("Falloff strength", Range(0.00001,10)) = 1.0
This is how they are defined in the CG Program section :
float3 _BendAmount;
float3 _BendOrigin;
float _BendFallOff;
float _BendFallOffStr;
Now let's look at the vertex shader:
v2f vert(appdata v)
{
 v2f o;
 o.vertex = UnityObjectToClipPos(curveIt(v.vertex));
 o.uv = v.uv;
 UNITY_TRANSFER_FOG(o,o.vertex);
 return o;
}
As you can we have a function called 'curveIt' which processes the input vertex values and passes it onto to be converted to clip space.
Now the gravy of the entire shader - The CurveIt Function:
float4 curveIt(float4 v)
{
 /*1*/float4 world = mul(unity_ObjectToWorld, v);
 /*2*/float dist = length(world.xyz - _BendOrigin.xyz);
 /*3*/dist = max(0, dist - _BendFallOff);

 /*4*/dist = pow(dist, _BendFallOffStr);
 /*5*/world.xyz += dist * _BendAmount;
 /*6*/return mul(unity_WorldToObject, world);
}
We will now go through those 6 lines of code that do all the magic.
  1. Getting world space location of a particular vertex and save it in 'world'
  2. Calculating the distance between the vertex position and where the _BendOrigin is.
  3. dist value is prevented from going below 0, This prevents undefined behaviour when using pow function (-ve values don't work with pow).
  4. dist value is raised to _BendFallOffStr value, which defines the steepness of the curve itself.
  5. _BendAmount should be dependent on the distance value(dist) so as to have a falloff curve, So we simply multiply it with dist and add to 'world' (position of vertex in world).
  6. convert the new world space of vertex and convert back to local( object ) space.
There are no changes to fragment shader in our case.
Now it's just a matter of playing around with the material properties. This shader works best when there are enough vertices to work with. So the default Unity cube is not a good candidate. The Unity plane is a better option but still it's not enough vertices to work with... so multiple Unity planes arranged in a grid with the Curved Surface shader applied on them is the best way to test it out quickly.... or you can make a high poly plane in Blender then import it.

To make the Gravity Displacement example shown above it's just a couple lines of code and attaching that to a sphere primitive.
using UnityEngine;
public class CurvedShaderTester : MonoBehaviour
{
    [SerializeField] private Material curvedSurfaceMat;
    void Start()
    {
        curvedSurfaceMat.SetVector("_BendAmount", new Vector3(0, 0.01f, 0));
        curvedSurfaceMat.SetFloat("_BendFallOff", -9.8f);
        curvedSurfaceMat.SetFloat("_BendFallOffStr", 2.0f);
    }
    void Update()
    {
        curvedSurfaceMat.SetVector("_BendOrigin", transform.position);
    }
}
That's literally it.
To make the Endless Runner example,we just have to modify the _BendAmount by keeping the y-axis bend as constant and changing the value either on the x-axis or z-axis depends on your case. This time instead of a sphere, We attach the script on the Camera itself.
using UnityEngine;
public class CurvedShaderTester : MonoBehaviour
{
    [SerializeField] private Material curvedSurfaceMat;
    void Start()
    {
        curvedSurfaceMat.SetFloat("_BendFallOff", 17.0f);
        curvedSurfaceMat.SetFloat("_BendFallOffStr", 2.0f);
    }

    void Update()
    {
        curvedSurfaceMat.SetVector("_BendOrigin", transform.position);
        curvedSurfaceMat.SetVector("_BendAmount", new Vector3(0, -0.01f, (Mathf.Sin(Time.time) * 0.03f)));
    }
}
Support Bitshift Programmer by leaving a like on Bitshift Programmer Facebook Page and be updated as soon as there is a new blog post.
If you have any questions that you might have about shaders, C# or Unity development in general don't be shy and leave a message on my facebook page or down in the comments.

For more shader goodness, Go HERE.
For Unity game development stuff, Go HERE.

Comments

  1. Great Tutorial , thank you.
    If you have the time a version fro Shader Graph would be awesome.

    ReplyDelete
    Replies
    1. https://www.youtube.com/watch?v=SOK3Ias5Nk0

      Delete

Post a comment

Assets Worth Checking Out

POPULAR POSTS

Introduction To Replacement Shaders & Shader Keywords

What is a replacement shader? A replacement shader is a shader that gets applied to every object being rendered.
Since the camera determines what objects end up being shown on screen, The functionality for setting up replacement shaders are in the camera class as well.

A good use case of a replacement shader would be in making effects like SSAO.
Here we need access to the normals and the depth information so a replacement shader that displays only the normals can be rendered ( stored in a render texture ) and then another shader that displays the depth information ( stored in a render texture ) and then the final image is rendered with the SSAO effect by taking the two render textures as input and doing a bunch of calculations.

Another use case would be to visualize the environment differently for various reasons like how they did in City Skylines.

The function that performs shader replacement is:
Camera.SetReplacementShader( Shader shader, string replacementTag ) Takes in a shader as …

Toon Liquid Shader - Unity Shader

Toon Liquid Shader This is how the shader will end up looking :
This shader is pretty neat and somewhat easy to implement as well as to understand. Since we will be adding some basic physics to the toon water as it is moved about we will have to support that in the vertex shader as well.
So let's start by looking at the properties :
Properties { _Colour ("Colour", Color) = (1,1,1,1) _FillAmount ("Fill Amount", Range(-10,10)) = 0.0 [HideInInspector] _WobbleX ("WobbleX", Range(-1,1)) = 0.0 [HideInInspector] _WobbleZ ("WobbleZ", Range(-1,1)) = 0.0 _TopColor ("Top Color", Color) = (1,1,1,1) _FoamColor ("Foam Line Color", Color) = (1,1,1,1) _Rim ("Foam Line Width", Range(0,0.1)) = 0.0 _RimColor ("Rim Color", Color) = (1,1,1,1) _RimPower ("Rim Power", Range(0,10)) = 0.0 } Just the usual stuff that we are used to. The only thing that may stand out is the [HideInInspector] tag, This works j…

Access Reflection Probe Data For Custom Shaders

The Unity shader documentation regarding reflection probes is pretty minimal and not at all comprehensive.
This short tutorial is intended to bring reflection probe functionalities to the forefront your future shader writing endevors which is a fancy way of saying "Look at this cool stuff and go and use it somewhere" 😏
Here we will try just the bare minimum of making a shader that reflects the cubemap data from reflection probe and displays it on the object.

These reflection probes are basically objects that store a complete image of the environment surrounding it into a cubemap which then can be read by shaders to create various effects.
More information on how reflection probes work in Unity can be found here :
Using Reflection Probes In Unity

I am not going over how to set up Reflection Probes here only how to access them inside our custom shaders.
So this is what we will be making:
The reflection probe takes in the cubemap only if it is within it's range otherwise i…

How To Animate A Fish Swimming With Shaders

Animate Fish Swimming With Shaders We are going to make swimming animation by using only shader code.
By the time we are done, it's going to look like this.
You will probably need the fish model used in this tutorial, that can be found HERE. Can use your own model but the shader code might have to be modified accordingly because of the orientation of the model that you might be using ( issues with whether the X axis & Z axis is flipped ).
The shader used way out performs a similar scene with skeletal animations applied on the fish models.
On a previous benchmark I did comparing the shader animation with the skeletal animation there was a difference of 28 FPS( on average ) with 50 fish.
The shader we are going to make is really powerful and flexible and don't think that it's limited to making fishes swim😀.


So this mesh oriented like this when imported into unity and this is important to understand because this means that the model's vertices have to be moved along the X-…