Unity 广告牌 (Billboard)的实现

2024-01-02 20:10

本文主要是介绍Unity 广告牌 (Billboard)的实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

实现一个广告牌的效果,使一个面片在摄像机旋转的过程中始终面向摄像机。

效果如下截图。

实现的Shader之一

(来自于冯姐Unity Shader入门精要十一章11.3.2的Shader)
// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'// Upgrade NOTE: replaced '_World2Object' with 'unity_WorldToObject'Shader "Unlit/fll-Billboard" {Properties {_MainTex ("Main Tex", 2D) = "white" {}_Color ("Color Tint", Color) = (1, 1, 1, 1)_VerticalBillboarding ("Vertical Restraints", Range(-5, 5)) = 2}SubShader {// Need to disable batching because of the vertex animationTags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" "DisableBatching"="True"}Cull offPass { Tags { "LightMode"="ForwardBase" }ZWrite OnBlend SrcAlpha OneMinusSrcAlphaCull OffCGPROGRAM#pragma vertex vert#pragma fragment frag#include "Lighting.cginc"sampler2D _MainTex;float4 _MainTex_ST;fixed4 _Color;fixed _VerticalBillboarding;struct a2v {float4 vertex : POSITION;float4 texcoord : TEXCOORD0;};struct v2f {float4 pos : SV_POSITION;float2 uv : TEXCOORD0;};v2f vert (a2v v) {v2f o;// Suppose the center in object space is fixedfloat3 center = float3(0, 0, 0);float3 viewer = mul(unity_WorldToObject,float4(_WorldSpaceCameraPos, 1));float3 normalDir = viewer - center;// If _VerticalBillboarding equals 1, we use the desired view dir as the normal dir// Which means the normal dir is fixed// Or if _VerticalBillboarding equals 0, the y of normal is 0// Which means the up dir is fixednormalDir.y =normalDir.y * _VerticalBillboarding;normalDir = normalize(normalDir);// Get the approximate up dir// If normal dir is already towards up, then the up dir is towards frontfloat3 upDir = abs(normalDir.y) > 0.999 ? float3(0, 0, 1): float3(0, 1, 0);float3 rightDir = normalize(cross(upDir, normalDir))*-1;upDir = normalize(cross(normalDir, rightDir));// Use the three vectors to rotate the quadfloat3 centerOffs = v.vertex.xyz - center;float3 localPos = center + rightDir * centerOffs.x + upDir * centerOffs.y + normalDir * centerOffs.z;o.pos = UnityObjectToClipPos(float4(localPos, 1));o.uv = TRANSFORM_TEX(v.texcoord,_MainTex);return o;}fixed4 frag (v2f i) : SV_Target {fixed4 c = tex2D (_MainTex, i.uv);c.rgb *= _Color.rgb;return c;}ENDCG}} FallBack "Transparent/VertexLit"
}

注意:代码中有一处需要修改,如下:

v2f vert (a2v v) {//*****float3 rightDir = normalize(cross(upDir, normalDir))*-1;//*****
}

乘以-1旋转方向,否则在Unity中可能出现翻转。

实现的Shader之二

来自于Wiki Cg_Programming(https://en.wikibooks.org/wiki/Cg_Programming/Unity/Billboards)

原代码:

Shader "Cg  shader for billboards" {Properties {_MainTex ("Texture Image", 2D) = "white" {}_ScaleX ("Scale X", Float) = 1.0_ScaleY ("Scale Y", Float) = 1.0}SubShader {Pass {   CGPROGRAM#pragma vertex vert  #pragma fragment frag// User-specified uniforms            uniform sampler2D _MainTex;        uniform float _ScaleX;uniform float _ScaleY;struct vertexInput {float4 vertex : POSITION;float4 tex : TEXCOORD0;};struct vertexOutput {float4 pos : SV_POSITION;float4 tex : TEXCOORD0;};vertexOutput vert(vertexInput input) {vertexOutput output;output.pos = mul(UNITY_MATRIX_P, mul(UNITY_MATRIX_MV, float4(0.0, 0.0, 0.0, 1.0))+ float4(input.vertex.x, input.vertex.y, 0.0, 0.0)* float4(_ScaleX, _ScaleY, 1.0, 1.0));output.tex = input.tex;return output;}float4 frag(vertexOutput input) : COLOR{return tex2D(_MainTex, float2(input.tex.xy));   }ENDCG}}
}

这段代码使用有一些限制:

  1. 不支持透明通道
  2. 当shader开启批处理时会产生显示错误,即当独享距离摄像机比较远时,对象会被裁剪
  3. 不能再Unity的Transform变换界面对其进行缩放和变换

修改后代码如下:

Shader "Unlit/fll-Billboard-2" {Properties {_MainTex ("Texture Image", 2D) = "white" {}_ScaleX ("Scale X", Float) = 1.0_ScaleY ("Scale Y", Float) = 1.0_Color("_Color",Color)=(1,1,1,1)}SubShader {Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" "DisableBatching"="True"}//Tags { "DisableBatching" = "True" }Pass {   	Tags { "DisableBatching" = "True" }ZWrite OnBlend SrcAlpha OneMinusSrcAlphaCull OffCGPROGRAM#pragma vertex vert  #pragma fragment frag#include "Lighting.cginc"// User-specified uniforms            uniform sampler2D _MainTex;        uniform float _ScaleX;uniform float _ScaleY;uniform fixed4 _Color;uniform float4 _MainTex_ST;struct vertexInput {float4 vertex : POSITION;float4 tex : TEXCOORD0;};struct vertexOutput {float4 pos : SV_POSITION;float2 tex : TEXCOORD0;//float2 uv:TEXCOORD1;};vertexOutput vert(vertexInput input) {vertexOutput output;output.pos = mul(UNITY_MATRIX_P, mul(UNITY_MATRIX_MV, float4(0.0, 0.0, 0.0, 1.0))+ float4(input.vertex.x, input.vertex.y, 0.0, 0.0)* float4(_ScaleX, _ScaleY, 1.0, 1.0));output.tex = TRANSFORM_TEX(input.tex,_MainTex);//output.uv=TRANSFORM_TEX(input.tex,_MainTex);//output.tex=input.tex;return output;}float4 frag(vertexOutput input) : SV_Target{fixed4 c=tex2D(_MainTex, float2(input.tex.xy));//return tex2D();   c.rgb*=_Color.rgb;return c;}ENDCG}}
}

绘制人物头顶到面片的线段代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class DrawLineRender : MonoBehaviour {public Color materialColor;LineRenderer lineRenderer_global;Vector3 startPos;Vector3 endPos;Vector3[] poss;[SerializeField]private Vector3 offset=Vector3.zero;[SerializeField][Range(0f,0.2f)]private float width=0.1f;void Awake () {LineRenderer lineRenderer = this.gameObject.AddComponent<LineRenderer> ();Material material=new Material(Shader.Find("Unlit/Color"));lineRenderer.material = material;lineRenderer.material.color = materialColor;lineRenderer.widthMultiplier = width;lineRenderer.positionCount = 2;lineRenderer.numCornerVertices=30;lineRenderer.numCapVertices=30;startPos = this.transform.parent.GetChild (2).transform.localPosition;endPos = this.transform.parent.GetChild (0).transform.localPosition;//var offset=new Vector3(0,1.254f,0);poss = new Vector3[2] { startPos-offset, endPos-offset };		}void Start(){lineRenderer_global= this.GetComponent<LineRenderer> ();}void Update () {for (int i = 0; i < lineRenderer_global.positionCount; i++) {lineRenderer_global.SetPosition (i, poss[i]);}}
}

工程地址->扫码->关注->历史消息->当前文章末尾


在这里插入图片描述

这篇关于Unity 广告牌 (Billboard)的实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/563519

相关文章

Flutter实现文字镂空效果的详细步骤

《Flutter实现文字镂空效果的详细步骤》:本文主要介绍如何使用Flutter实现文字镂空效果,包括创建基础应用结构、实现自定义绘制器、构建UI界面以及实现颜色选择按钮等步骤,并详细解析了混合模... 目录引言实现原理开始实现步骤1:创建基础应用结构步骤2:创建主屏幕步骤3:实现自定义绘制器步骤4:构建U

SpringBoot中四种AOP实战应用场景及代码实现

《SpringBoot中四种AOP实战应用场景及代码实现》面向切面编程(AOP)是Spring框架的核心功能之一,它通过预编译和运行期动态代理实现程序功能的统一维护,在SpringBoot应用中,AO... 目录引言场景一:日志记录与性能监控业务需求实现方案使用示例扩展:MDC实现请求跟踪场景二:权限控制与

Android实现定时任务的几种方式汇总(附源码)

《Android实现定时任务的几种方式汇总(附源码)》在Android应用中,定时任务(ScheduledTask)的需求几乎无处不在:从定时刷新数据、定时备份、定时推送通知,到夜间静默下载、循环执行... 目录一、项目介绍1. 背景与意义二、相关基础知识与系统约束三、方案一:Handler.postDel

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义