相机渲染纹理中的透明度

问题描述 投票:0回答:2

在我的 Unity 项目中,我致力于将视图从相机渲染到 Texture2D。我创建了一个 RenderTexture 来捕获相机的输出,然后将其复制到 Texture2D。但是,我遇到了一个问题,我需要生成的图像具有透明背景。到目前为止我找到的唯一解决方案是将相机的背景设置为透明。但是,我仍然必须指定一种颜色,并且这种颜色在图像的所有半透明区域都可见。

Look at this.

白框中可以看到RenderTexture中得到的最终结果

您是否碰巧知道任何其他方法来获得具有适当透明度的相机图像?

unity-game-engine texture2d alpha-transparency
2个回答
0
投票

清除标志文档:https://docs.unity3d.com/ScriptReference/Camera-

CameraClearFlags.Nothing
似乎是你想要的。


0
投票

感谢@mrVentures 的建议;我尝试实施它。 RenderTexture 会累积图像而不清除,因此在复制之前,需要清除并渲染单帧。如果有人需要,这是我的代码。

public void clearTexture(RenderTexture texture) {
    RenderTexture.active = texture;
    GL.Clear(true, true, Color.clear);
    RenderTexture.active = null;

    // texture.Release();  — another option
}

public Texture2D getTextureFromCamera(Camera camera) {
    RenderTexture rt = camera.targetTexture;
    clearTexture(rt);
    viewCamera.Render();
    
    Texture2D tex = new Texture2D(rt.width, rt.height, TextureFormat.RGBA32, false);
    RenderTexture.active = rt;
    tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
    tex.Apply();
    RenderTexture.active = null;

    return tex;
}

不幸的是,结果与我使用带有黑色透明背景的 CameraClearFlags.Color 时完全相同。结果,黑色的半透明阴影变得更暗,明亮的颜色获得了黑暗的光晕。这远非预期的结果。 The result

你有什么其他的想法我可以尝试吗?我想到了单独获取 alpha 通道并以某种方式烘焙纹理,以便图像的半透明区域不透明。但是,我不知道如何做到这一点。

© www.soinside.com 2019 - 2024. All rights reserved.