Unity 2D游戏背景滚动

代码 一:

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图上)
  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值