unity---背景循环滚动

时间:2021-11-14 17:02:10

方法一:场景创建Sprite

Transform position 为0

复制第二张 Y 位置为 图片像素/ Pixel Per Unit100

unity---背景循环滚动

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//这里脚本挂到了管理上
public class MainManager : MonoBehaviour
{
Transform bg1Spr, bg2Spr;
Transform[] BgSprites;
public float moveSpeed = 5f;
private void Awake()
{
bg1Spr = transform.Find("BgGround/bg1");
bg2Spr = transform.Find("BgGround/bg2");
}
void Start()
{
BgSprites = new Transform[] { bg1Spr, bg2Spr };
} void Update()
{
Vector3 translate = Vector3.down * Time.deltaTime * this.moveSpeed;
for (int i = 0; i < BgSprites.Length; i++)
{
BgSprites[i].Translate(translate);
if (BgSprites[i].position.y < -19.49f)
{
BgSprites[i].position += new Vector3(0, 19.49f * 2, 0);
}
}
}
}

方法二:利用shader

unity---背景循环滚动

unity---背景循环滚动

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI; public class GameManager : MonoBehaviour
{
float moveSpeed = 0.1f;
Material material;
private void Awake()
{
material = transform.Find("UIPanel/Bg/bg1").GetComponent<Image>().material;
}
float y;
public float Y
{
get { return y; }
set { y = value; }
} void Update()
{ Y += Time.deltaTime * moveSpeed;
//给shader里对应的字段赋值
material.SetTextureOffset("_MainTex", new Vector2(0, Y));
// material.mainTextureOffset = new Vector2(0, Y); }
}

http://www.ceeger.com/Script/Material/Material.SetTextureOffset.html#

参考:https://fengyu.name/article/311