Unity贴花效果
方法一(业余):
效果
shader:
Shader "MJ/ForwardDecal"
{
Properties
{
_MainTex ("Decal Texture", 2D) = "white" {}
}
SubShader
{
Tags{ "Queue"="Geometry+1" }
Pass
{
ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma target 3.0
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct v2f
{
float4 pos : SV_POSITION;
float4 screenUV : TEXCOORD0;
float3 ray : TEXCOORD1;
};
v2f vert (appdata_base v)
{
v2f o;
o.pos = UnityObjectToClipPos (v.vertex);
o.screenUV = ComputeScreenPos (o.pos);
o.ray = UnityObjectToViewPos(v.vertex).xyz * float3(-1,-1,1);
return o;
}
sampler2D _MainTex;
sampler2D _CameraDepthTexture;
float4 frag(v2f i) : SV_Target
{
i.ray = i.ray * (_ProjectionParams.z / i.ray.z);
float2 uv = i.screenUV.xy / i.screenUV.w;
float depth = SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, uv);
// 要转换成线性的深度值 //
depth = Linear01Depth (depth);
float4 vpos = float4(i.ray * depth,1);
float3 wpos = mul (unity_CameraToWorld, vpos).xyz;
float3 opos = mul (unity_WorldToObject, float4(wpos,1)).xyz;
clip (float3(0.5,0.5,0.5) - abs(opos.xyz));
// 转换到 [0,1] 区间 //
float2 texUV = opos.xz + 0.5;
float4 col = tex2D (_MainTex, texUV);
return col;
}
ENDCG
}
}
Fallback Off
}
这样最明显的一个问题就是只能朝固定方向绘制,绘制在物体侧面时图像会被拉伸,这样不好,不过
可以这样,新建脚本(我挂在相机上):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraRay : MonoBehaviour
{
private Ray ray;
private RaycastHit hit;
public Transform Decal;
void Update()
{
if (Input.GetMouseButton(0))
ray = Camera.main.ScreenPointToRay(Input.mousePosition);//摄像机发射射线到屏幕点。
else if (Input.GetMouseButtonUp(0))
ray = new Ray();
if (Physics.Raycast(ray, out hit))
{
Decal.position = hit.point;
Vector3 pos = hit.collider.transform.position;
Decal.LookAt(pos);
}
}
}
拖入相关节点(这个节点是一个空节点,子节点就是使用了上方shader的cube物体)
运行
贴在单个物体(长款高比例接近1的物体)上转折处效果较好,在在组合物体上时依然会有异常拉伸
方法二(专业):
使用unity插件"DynamicDecals"
链接里是一个unity工程,demo效果很nice,想办法把插件从里边抽出来你就能用啦
方法三(专业):
unity 官方有一个Demo:
链接:https://pan.baidu.com/s/1IHcn1JDiAlK2Ejax4Pvxdg
提取码:wrva
参考原文地址:https://blog.csdn.net/h5502637/article/details/86524543