【Unity】刮刮乐案例-RenderTexture实现思路

Demo资源包可直接导入Unity工程使用

通过网盘分享的文件:GuaGuaLeDemo.unitypackage

链接: https://pan.baidu.com/s/1OaGO8Mvi0BYUaenLrBRC9g?pwd=2i76 提取码: 2i76

原理:使用 Graphics.DrawTexture API 初始写入一张纯透明纹理到RT纹理(64x32),用户操作鼠标按下时将点击屏幕坐标经过一系列转化为RT纹理空间的UV坐标,在该UV坐标上绘制一张刮痕纹理(8x8)不透明图写入RT纹理。其中,RT纹理会交由GuaGuaLeMat材质球进行透明度混合渲染,输出透明度值 = 原图(灰色)透明度1 * (1 - RT纹理透明度) 输出,输出RGB值不变。

【RT纹理透明度会从全图初始0,不断由玩家控制写入不透明图而变为全图1的透明值】

【透明度1是指完全不透明图,透明度0,1变化 】

核心部分:Mask 可操作区域 (500x250) 可自定义区域

GuaGuaLe.cs脚本参数说明

RT: 一张64*32大小的R32G32B32A32_SINT格式的2D渲染纹理,注意一定要使用R32G32B32A32_SINT格式,也可以是更小精度的16,但必须保证是_SINT 整型的,不然会出现混合RT纹理后,颜色混合重叠次数过多导致刮痕区域颜色曝光变色效果(无法显示背后的正常绿色,可能会显示出黄色!)

Default Img:一张64*32的纯透明图,作为RT图的初始化写入纹理,资源如下(纯透明)


Draw Img:一张8*8的不透明图,作为实时写入的刮痕纹理(刮掉的区域),资源如下(纯白)

Rect Transform:Canvas的RectTransform,用于屏幕转局部UI空间坐标

UICamera:Canvas的UI摄像机

GuaGuaLe.cs脚本

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GuaGuaLe : MonoBehaviour
{
    public RenderTexture rt;

    //参与渲染的默认纹理(透明度全为0的透明图)
    public Texture defaultImg;

    //参与渲染的刮痕纹理(透明度为1的纹理)
    public Texture drawImg;

    public RectTransform rectTransform;
    public Camera uiCamera;

    private Image maskImg;

    // Start is called before the first frame update
    void Start()
    {
        maskImg = GetComponent<Image>();

        DrawDefault();
    }

    private void OnDestroy()
    {
        DrawDefault();
    }

    void DrawDefault()
    {
        //初始化将默认纹理写入rt渲染纹理,参与渲染Mask
        //Mask材质会处理透明度混合,输出原纹理rgb, 原纹理透明度 *(1-rt纹理透明度) 即显示原纹理,因为目前rt纹理透明度是0 【defaultImg是目前的rt纹理】
        RenderTexture.active = rt;
        GL.PushMatrix();
        GL.LoadPixelMatrix(0, rt.width, rt.height, 0);

        Rect rect = new Rect(0, 0, rt.width, rt.height);
        Graphics.DrawTexture(rect, defaultImg);

        GL.PopMatrix();

        RenderTexture.active = null;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            Vector2 pos;
            bool isOK = RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, Input.mousePosition, uiCamera, out pos);
            if (isOK)
            {
                //通过打印观察发现pos范围是x[-250,250],y[-125,125] 需转为左下角(0,0)为起点的坐标
                //Debug.Log(pos);
                //故直接加上(250,125)即可,这个值是Mask刮痕区域的大小一半
                pos += maskImg.rectTransform.sizeDelta / 2f;
                //归一化
                pos.x /= maskImg.rectTransform.sizeDelta.x;
                pos.y /= maskImg.rectTransform.sizeDelta.y;
                //Debug.Log("转后:" + pos);

                //归一化坐标转化为rt纹理空间坐标
                pos.x *= rt.width;
                pos.y *= rt.height;
                //由于Shader UV空间左上角是(0,0),故需将Y值颠倒 [即原左上角(0,rt.height)变为(0,0), 原左下角(0,0)变为(0,rt.height)]
                pos.y = rt.height - pos.y;

                RenderTexture.active = rt;
                GL.PushMatrix();
                GL.LoadPixelMatrix(0, rt.width, rt.height, 0);

                //将坐标往左下偏移一半drawImg区域,得到绘制起点(即将绘制区域的左下角位置点)
                pos.x -= (int)(drawImg.width / 2f);
                pos.y -= (int)(drawImg.height / 2f);

                Rect rect = new Rect(pos.x, pos.y, drawImg.width, drawImg.height);
                Graphics.DrawTexture(rect, drawImg);

                GL.PopMatrix();

                RenderTexture.active = null;
            }
        }
    }
}

GuaGuaLeShader着色器

cs 复制代码
Shader "Unlit/GuaGuaLeShader"
{
    Properties
    {
        //如果你有刮痕区域的主纹理,可以使用_MainTex参数,而不使用_MainColor 我这里是直接用这个_MainColor作为刮痕区域颜色值
        //_MainTex ("Texture", 2D) = "white" {}
        _MainColor ("Main Color", Color) = (1,1,1,1)
        _RenderTexture ("Render Texture", 2D) = "white"{}
    }
    SubShader
    {
        Blend SrcAlpha OneMinusSrcAlpha
        Tags { "RenderType"="Transparent" "Queue"="Transparent" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            //sampler2D _MainTex;
            //float4 _MainTex_ST;

            sampler2D _RenderTexture;

            fixed4 _MainColor;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                //o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                o.uv = v.uv;

                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_RenderTexture, i.uv);
                
                //① _MainColor作为主纹理颜色方案
                return fixed4(_MainColor.rgb, _MainColor.a * (1 - col.a));

                //② 若你有主纹理需求,则使用如下2行代码 替代[①]方案代码
                //fixed4 mainCol = tex2D(_MainTex, i.uv);
                //return fixed4(mainCol.rgb, mainCol.a * (1 - col.a));
            }
            ENDCG
        }
    }
}
相关推荐
学术小李9 小时前
用虚幻引擎(UE)打开Obj模型
游戏引擎·虚幻
张不无-Unity10 小时前
Unity的四种灯光Directional、Point、Spot 和 Area
unity·游戏引擎
淡海水2 天前
02-02-原理篇-Scriban模板引擎原理深度解析
unity·excel·游戏开发·luban
ttod_qzstudio3 天前
系统架构设计师论文逐句拆解(三):ATAM 架构评估,怎样把“方案比较”写成质量属性权衡
unity·架构·系统架构·软考
小贺儿开发4 天前
Unity 轻量级外部素材加载器(热更新)
科技·学习·unity·程序员·工具·热更新·ugui
淡海水6 天前
01-03-认知篇-基础-Excel配置工作流痛点深度分析
unity·架构·excel·游戏开发·luban
谙弆悕博士6 天前
生物启发式集群(Swarm)工程实现:五条规则、一群蚂蚁和四十个粒子
人工智能·gpt·游戏引擎·cocos2d·蚁群算法·多智能体·boids
Frankie_stand7 天前
无人机售后故障处理全流程:从受理、SLA 时限到责任划分与改进闭环
游戏引擎·无人机·cocos2d
zdr尽职尽责15 天前
UnityCli 兼容2022版本
ui·unity·ai·c#·游戏引擎