Unity 两张背景的切换平移

image

两张背景图片向左移动,当屏幕看见的时候. 使用的是Unity自带的Sprite,当然也可以使用NGUI Sprite

using UnityEngine;

using System.Collections;



/**

 *两个背景图片平移 

 */

public class BackgroundController : MonoBehaviour {





    public SpriteRenderer back1;        

    public SpriteRenderer back2;        

    public Sprite [] textureList;           //背景图片集合

     public int speed = 1;                   //背景平移的速度

     public Transform endPosition;           //到达该位置,把背景移动到开始位置

     public Transform startPosition;         //背景从开始位置移动到结束位置

        

    private int backIndex;                  



    void Start() 

    {

        back1.sprite = textureList[0];

        back2.sprite = textureList[1];

        backIndex = 2;

    }



    void Update() 

    {

        if (backIndex >= textureList.Length) 

        {

            backIndex = textureList.Length - 1;

        }



        //两个图片的平移

        back1.transform.position = new Vector3(back1.transform.position.x - speed * Time.deltaTime, back1.transform.position.y, back1.transform.position.z);

        back2.transform.position = new Vector3(back2.transform.position.x - speed * Time.deltaTime, back2.transform.position.y, back2.transform.position.z);



        //到达结束位置,回到开始位置,切换图片

        if (back1.transform.position.x <= endPosition.transform.position.x) 

        {

            back1.transform.position = startPosition.position;

            back1.sprite = textureList[backIndex];

            backIndex++;

        }



        if (back2.transform.position.x <= endPosition.transform.position.x)

        {

            back2.transform.position = startPosition.position;

            back2.sprite = textureList[backIndex];

            backIndex++;

        }

    }



}

你可能感兴趣的:(unity)