代码 一:
Canvas 的Render Mode 为 Screen Space-Overly 可用
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BgCycle : MonoBehaviour
{
public int speed = 4;
public BgCycle Next;
private float minX;
private float screenHalf_x = 0;
void Start()
{
screenHalf_x = Screen.width*0.5f;
minX = 0 - screenHalf_x;
}
void Update()
{
if (transform.position.x <= minX)
{
transform.position = new Vector3(Next.transform.position.x+ screenHalf_x*2, transform.position.y, transform.position.z);
}
transform.Translate(Vector3.left * Time.deltaTime * speed);
}
}
- 声明:
speed
: 背景移动的速度。
Next
: 当前背景的下一个背景对象,用于实现循环。
-
计算屏幕宽度的一半 (Start
方法:screenHalf_x
),用于计算背景移动的边界。
计算背景循环的最小 x 坐标 (minX
),用于判断背景是否需要重置位置。
-
Update
方法:
每帧检查背景的 x 坐标是否小于等于 minX
。如果是,则将背景的位置重置到下一个背景的位置加上两个屏幕宽度,从而实现背景的无缝循环。
背景会根据 speed
变量设置的速度向左移动。
代码二:
Canvas 的Render Mode 的三个模式都可以 ,滚动速度: 同一数值 ,快慢不同
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BgCycle : MonoBehaviour
{
public int speed = 4;
public BgCycle Next;
public float minX;
private float screenHalf_x = 0;
void Start()
{
screenHalf_x = Screen.width;
minX = 0 - screenHalf_x;
}
void Update()
{
if (transform.localPosition.x <= minX)
{
transform.localPosition = new Vector3(Next.transform.localPosition.x+ screenHalf_x, transform.localPosition.y, transform.localPosition.z);
}
transform.Translate(Vector3.left * Time.deltaTime * speed);
}
}
使用:
- 至少需要三张图片
- 将代码挂载到带有Image组件上面(Bg图上)