Search Unity

Question How to add 2 semi-transparent colors?

Discussion in 'General Graphics' started by SinSinx2, Jun 5, 2023.

  1. SinSinx2

    SinSinx2

    Joined:
    Mar 13, 2019
    Posts:
    12
    I have to copy pixels from one texture on top of another texture but some of the pixels are half transparent which means that instead of overwriting the pixel info, I need to add it to the current color.

    I tried doing color + color but that leads to something completely broken.

    upload_2023-6-5_13-50-13.png

    Here is what the 2 textures look like when overlayed in the editor.

    upload_2023-6-5_13-51-4.png

    I have tried other methods but those didn't work either. Does anybody know how to do this through code?

    EDIT: The background is a solid color
     
    Last edited: Jun 5, 2023
  2. SinSinx2

    SinSinx2

    Joined:
    Mar 13, 2019
    Posts:
    12
    I figured it out. The code for multiplying 2 pixels is as follows

    Code (CSharp):
    1. Color currPixel = image1.texture.GetPixel(x1, y1);
    2. Color newPixel = image2.texture.GetPixel(x2, y2);
    3.  
    4. Color mixedPixel = new Color(
    5.     (currPixel.r * (1f - newPixel.a) + newPixel.r * newPixel.a),
    6.     (currPixel.g * (1f - newPixel.a) + newPixel.g * newPixel.a),
    7.     (currPixel.b * (1f - newPixel.a) + newPixel.b * newPixel.a),
    8.     Mathf.Clamp01(currPixel.a + newPixel.a)
    9.     );
    10.  
    I actually made a mistake while grabing the current pixel and used x2 and y2 instead which is why I couldn't get it to work.