赞
踩
2D游戏中,背景图轮换是一个非常常用的场景,轮换的方式现在有两种,一种是两张图片不断改变坐标
另一种是使用shader,原理相同,同样都是坐标轮换
两张图片不断改变坐标,当第二张到达第一张图片图片的位置,两个交换循环:
布局如图
代码绑定在BG上,代码如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Background : MonoBehaviour { // Start is called before the first frame update private GameObject background1; private GameObject background2; public GameObject swap; public int speed = 4; private Vector3 startPosition; private Vector3 endPosition; void Start() { background1 = transform.Find("Background1").gameObject; background2 = transform.Find("Background2").gameObject; startPosition = background1.transform.position; endPosition = background2.transform.position; } // Update is called once per frame void Update() { background1.transform.Translate(Vector3.left * Time.deltaTime * speed, Space.World); background2.transform.Translate(Vector3.left * Time.deltaTime * speed, Space.World); if (background2.transform.position.x < startPosition.x) { background1.transform.position = endPosition; swap = background1; background1 = background2; background2 = swap; } } }
布局:
Shader "Custom/LooperBgShader" { Properties { _Color ("Color", Color) = (1,1,1,1) _MainTex ("Albedo (RGB)", 2D) = "white" {} _MainTex1 ("Albedo (RGB)", 2D) = "white" {} _Glossiness ("Smoothness", Range(0,1)) = 0.5 _Metallic ("Metallic", Range(0,1)) = 0.0 } SubShader { Pass{ CGPROGRAM // Physically based Standard lighting model, and enable shadows on all light types // Use shader model 3.0 target, to get nicer looking lighting #pragma target 3.0 #include "UnityCG.cginc" sampler2D _MainTex; sampler2D _MainTex1; float4 _MainTex_ST; float4 _MainTex1_ST; struct a2v { float4 vertex : POSITION; float4 texcoord : TEXCOORD0; }; struct v2f { float4 pos : SV_POSITION; float4 uv : TEXCOORD0; // uv中xy变量记录背景1,zw变量记录背景2 }; int _ScrollX = 1; int _Scroll2X = 1; // 顶点着色器中实现图像的移动,用速度*_Time.y来实现 v2f vert (a2v v) { v2f o; o.pos = UnityObjectToClipPos(v.vertex); // 背景1,坐标位置+横向移动量 o.uv.xy = TRANSFORM_TEX(v.texcoord, _MainTex) + frac(float2(_ScrollX, 0.0) * _Time.y); // 背景2,坐标位置+横向移动量 o.uv.zw = TRANSFORM_TEX(v.texcoord, _MainTex1) + frac(float2(_Scroll2X, 0.0) * _Time.y); return o; } _Multiplier = 1.0f fixed4 frag (v2f i) : SV_Target { //对两张纹理进行采样 fixed4 firstLayer = tex2D(_MainTex, i.uv.xy); fixed4 secondLayer = tex2D(_MainTex1, i.uv.zw); //使用第二层纹理的透明通道来混合两张纹理,使用CG的lerp函数 fixed4 c = lerp(firstLayer, secondLayer, secondLayer.a); //使用_Multiplier参数和输出颜色相乘,调整背景亮度 c.rgb *= _Multiplier; return c; } ENDCG } } FallBack "Diffuse" }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。