Shader achieves the effect of liquid in the bottle

Not much to say, first picture...
Insert picture description here

Full source code address:

https://blog.csdn.net/ww1351646544/article/details/104917031

demand:

1. The liquid effect can change color.
2. The liquid is transparent and has a refraction effect.
3. Adapt to various container shapes.
4. Dithering with the moving amplitude.

Realization ideas:

1. The realization of horizontal plane
This is relatively simple, set a certain height, and if there is more than this height, a piece of original will be discarded. However, the local coordinates of the height of the fragment and the height of the real contrast are the world coordinates, so there needs to be a coordinate conversion operation.
Set a value that is the world coordinate height of the clipping of the current point , which is passed in by an external script.
Then the height of each fragment is converted into world coordinates and compared with it to decide whether to discard it.
Note: Turn off the cutting of the back element , otherwise the back will be incomplete when viewed from the top.

2. Adapt to the container.
Copy a container as a liquid, shrink it to a little smaller than the container itself , and place this liquid shader.

3. The left and right jitter of the liquid is
based on the X value of the center point. Subtract the X of the center point from the current point X to get a distance (this distance can be positive or negative). This distance is used to affect the horizontal plane height in question 1. . A jitter value (positive and negative) comes in from the outside to affect the amplitude of the jitter, and the positive and negative are used to control the direction of the jitter, so as to achieve the effect of liquid jitter.

4. Calculating the amplitude of jitter (this part is implemented with C# code)
each movement will record the position of each frame in lastPos, and record each lastPos in the array, and then assign the current position to lastPos until lastPos equals the current Position, and there is a position record in the collocated array (this means that the object has been moved and moved completely). At this time, the average value of all records in the array is calculated, and the speed of this movement can be known to obtain the amplitude of the jitter.
Floating left and right swings are realized with sine waves, and the amplitude gradually weakens.

Core code:

//与中心点距离(_LevelOfWaterOffsetScale是有正负值的摆动比例)
float centerDistance = (worldPos.x -_LevelOfWaterX)*_LevelOfWaterOffsetScale;

//波动值影响裁剪高度
float heightOffset = _LevelOfWaterY +centerDistance;

//高于指定高度则裁剪
if(worldPos.y>heightOffset)clip(-1);

Welcome everyone to communicate and correct : QQ: 262319244
I hope to have a better way to communicate with me, and at the same time solicit ideas for the realization of liquid water, as shown below:
Insert picture description here

Guess you like

Origin blog.csdn.net/ww1351646544/article/details/98632525