So I have been trying to replicate the native unity functionality of overlapping transparent sprites but I’m having difficulty getting it exactly correct… I have been using this code to calculate each rgb color based on alpha:
Essentially it is overlaying a foreground color to a background color, however it seems this code assumes the background will never be transparent, I wonder if there is a variation that allows for a transparent background?
These are my results; on the left the color created by script and on the right 2 square sprites overlapped in an empty object grabbing each their respective color( blended automatically by unity)
^ but when i make the background transparent it breaks, while there shouldn’t be any red value on the final color its clear that the code is taking red from the invisible background and mixing it with the overlay color, the unity blend on the right clearly shows what the color should look like
If anyone has a solution it would be greatly appreciated, thanks in advance! =)
The formula that you posted doesn’t use the background alpha for anything. Have you tried actually using the background alpha instead of (1 - OverlayAlpha)?
You need to calculate the alpha and color separately, otherwise you’re multiplying the alpha by itself. You’re calculating a premultiplied alpha color, so if you want to use this with a traditional Blend SrcAlpha OneMinusSrcAlpha shader, you need to correct for that by dividing the color value by the alpha. Otherwise you can use a Blend One OneMinusSrcAlpha shader instead.
Psuedo-code below (written like an hlsl shader, which you can’t really do in C#, unless you’re using Unity’s Mathematics library)