【Unity3D】实现云循环漂浮效果

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 
/// CloudFlow说明
///
/// 1.该脚本挂在Cloud Object上;
/// 2.将背景挂在Inspecter中到“_背景”中;
/// 3.“_从左到右”值,勾选左到右,不勾选右到左;
/// 4.“_速度”改变云漂浮速度
/// 5.“_离开画面距离”,决定云离开画面多远开始从另一边循环
/// 6.“_上下浮动效果”勾选开启浮动效果,默认不开启;
/// 
/// </summary>

public class CloudFlow : MonoBehaviour
{
    public bool _从左到右 = true;
    public float _速度 = 2;
    public float _离开画面程度 = 5;
    public BoxCollider2D _背景;
    public bool _上下浮动效果 = false;
    public float _上下浮动幅度 = 5;
    public float _上下浮动速度 = 5;

    private float x_开始位置, x_结束位置;
    private float _正向系数 = 1;
    private float y_中心位置;
    private static float radian_0_1 = 0;

    void Start()
    {
        PosInitialize();
    }

    void Update()
    {
        Flow();
        if (_上下浮动效果)
        {
            VerticalFlow(); 
        }
        if (isArriveMargin())
        {
            ChangePos();
        }
    }
    //上下浮动方法
    public void VerticalFlow()
    {
        radian_0_1 += _上下浮动速度*0.001f;
        float dy = Mathf.Cos(radian_0_1) * 0.1f * _上下浮动幅度;
        transform.position = new Vector3(transform.position.x, y_中心位置 + dy, transform.position.z);
    }
    //参数初始化方法
    public void PosInitialize()
    {
        if (_从左到右)
        {
            _正向系数 = 1;
            x_结束位置 = _背景.bounds.max.x + _离开画面程度+2;
            x_开始位置 = _背景.bounds.min.x - _离开画面程度-2;
        }
        else
        {
            _正向系数 = -1;
            x_开始位置 = _背景.bounds.max.x + _离开画面程度+2;
            x_结束位置 = _背景.bounds.min.x - _离开画面程度-2;
        }
        y_中心位置 = transform.position.y;
    }
    //横向漂动方法
    public void Flow()
    {
        this.transform.position += new Vector3(_正向系数 * _速度 * 0.01f, 0, 0);
    }
    //判断是否该归位方法
    public bool isArriveMargin()
    {
        return (_从左到右 && transform.position.x > x_结束位置) || (!_从左到右 && transform.position.x < x_结束位置);
    }
    //循环归位方法
    public void ChangePos()
    {
        transform.position = new Vector3(x_开始位置, transform.position.y, transform.position.z);
    }


}
原文地址:https://www.cnblogs.com/garychen97/p/14371518.html