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

相关文章

基于C++的UDP网络通信系统设计与实现详解

《基于C++的UDP网络通信系统设计与实现详解》在网络编程领域,UDP作为一种无连接的传输层协议,以其高效、低延迟的特性在实时性要求高的应用场景中占据重要地位,下面我们就来看看如何从零开始构建一个完整... 目录前言一、UDP服务器UdpServer.hpp1.1 基本框架设计1.2 初始化函数Init详解

Java中Map的五种遍历方式实现与对比

《Java中Map的五种遍历方式实现与对比》其实Map遍历藏着多种玩法,有的优雅简洁,有的性能拉满,今天咱们盘一盘这些进阶偏基础的遍历方式,告别重复又臃肿的代码,感兴趣的小伙伴可以了解下... 目录一、先搞懂:Map遍历的核心目标二、几种遍历方式的对比1. 传统EntrySet遍历(最通用)2. Lambd

springboot+redis实现订单过期(超时取消)功能的方法详解

《springboot+redis实现订单过期(超时取消)功能的方法详解》在SpringBoot中使用Redis实现订单过期(超时取消)功能,有多种成熟方案,本文为大家整理了几个详细方法,文中的示例代... 目录一、Redis键过期回调方案(推荐)1. 配置Redis监听器2. 监听键过期事件3. Redi

SpringBoot全局异常拦截与自定义错误页面实现过程解读

《SpringBoot全局异常拦截与自定义错误页面实现过程解读》本文介绍了SpringBoot中全局异常拦截与自定义错误页面的实现方法,包括异常的分类、SpringBoot默认异常处理机制、全局异常拦... 目录一、引言二、Spring Boot异常处理基础2.1 异常的分类2.2 Spring Boot默

基于SpringBoot实现分布式锁的三种方法

《基于SpringBoot实现分布式锁的三种方法》这篇文章主要为大家详细介绍了基于SpringBoot实现分布式锁的三种方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、基于Redis原生命令实现分布式锁1. 基础版Redis分布式锁2. 可重入锁实现二、使用Redisso

SpringBoo WebFlux+MongoDB实现非阻塞API过程

《SpringBooWebFlux+MongoDB实现非阻塞API过程》本文介绍了如何使用SpringBootWebFlux和MongoDB实现非阻塞API,通过响应式编程提高系统的吞吐量和响应性能... 目录一、引言二、响应式编程基础2.1 响应式编程概念2.2 响应式编程的优势2.3 响应式编程相关技术

C#实现将XML数据自动化地写入Excel文件

《C#实现将XML数据自动化地写入Excel文件》在现代企业级应用中,数据处理与报表生成是核心环节,本文将深入探讨如何利用C#和一款优秀的库,将XML数据自动化地写入Excel文件,有需要的小伙伴可以... 目录理解XML数据结构与Excel的对应关系引入高效工具:使用Spire.XLS for .NETC

Nginx更新SSL证书的实现步骤

《Nginx更新SSL证书的实现步骤》本文主要介绍了Nginx更新SSL证书的实现步骤,包括下载新证书、备份旧证书、配置新证书、验证配置及遇到问题时的解决方法,感兴趣的了解一下... 目录1 下载最新的SSL证书文件2 备份旧的SSL证书文件3 配置新证书4 验证配置5 遇到的http://www.cppc

Nginx之https证书配置实现

《Nginx之https证书配置实现》本文主要介绍了Nginx之https证书配置的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起... 目录背景介绍为什么不能部署在 IIS 或 NAT 设备上?具体实现证书获取nginx配置扩展结果验证

SpringBoot整合 Quartz实现定时推送实战指南

《SpringBoot整合Quartz实现定时推送实战指南》文章介绍了SpringBoot中使用Quartz动态定时任务和任务持久化实现多条不确定结束时间并提前N分钟推送的方案,本文结合实例代码给大... 目录前言一、Quartz 是什么?1、核心定位:解决什么问题?2、Quartz 核心组件二、使用步骤1