Last active
February 28, 2019 10:59
-
-
Save tamask/126f4b7aa0b9c308eb8eab192f77f768 to your computer and use it in GitHub Desktop.
Matrix for shader-based billboarding in Unity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef _BILLBOARD | |
#define _BILLBOARD | |
#include "UnityCG.cginc" | |
/* | |
About BILLBOARD_MATRIX | |
---------------------- | |
This custom matrix is a rotation transformation matrix derived from | |
the rotation part of the current camera's view matrix, | |
UNITY_MATRIX_V. This is for a shader-based 'billboard effect' per | |
quad. | |
Using this custom matrix depends on the quad being centered at the | |
model's local origin. The mesh generated RandomQuadBox generates quads | |
centered like this. But, if your quad already has a translation away | |
from the origin on the CPU side some additional steps and data are | |
required: | |
1. Store the delta translation of the quad's center from the model | |
origin. You can store this as a Vector3 across two UV channels | |
for the four vertices that contribute to the given quad, for | |
example: vec.xyz -> uv1.x, uv1.y, uv2.x. | |
2. In the vertex program, construct a float3 vector from the uv data | |
channels (vec.xyz <- uv1.x, uv1.y, uv2.x), and negate this offset | |
from the vertex position in local model space, *before* | |
BILLBOARD_MATRIX. | |
3. Then multiply by BILLBOARD_MATRIX, as seen in the pseudocode | |
below. | |
4. Add the offset back to the quad's vertices. | |
Some pseudo code to demonstrate the steps above: | |
float3 offset = float3(v.uv1.x, v.uv1.y, v.uv2.x); | |
v.vertex.xyz -= offset.xyz; | |
v.vertex = mul(v.vertex, BILLBOARD_MATRIX); | |
v.vertex.xyz += offset.xyz; | |
o.vertex = UnityObjectToClipPos(v.vertex); | |
*/ | |
#define BILLBOARD_MATRIX \ | |
float4x4( \ | |
normalize(UNITY_MATRIX_V._m00_m01_m02), 0, \ | |
normalize(UNITY_MATRIX_V._m10_m11_m12), 0, \ | |
normalize(UNITY_MATRIX_V._m20_m21_m22), 0, \ | |
0, 0, 0, 1) | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment