1. 程式人生 > >關卡選擇可以拖動的例子(水平)

關卡選擇可以拖動的例子(水平)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

//選擇關卡的效果,有四頁的選擇
public class LevelButtonListRect : MonoBehaviour,IBeginDragHandler,IEndDragHandler {
    private ScrollRect scrollRect;
    public float smoothing = 4;
    private float[] pageArray = new float[] { 0, 0.3333f, 0.6666f, 1 };  //分四頁  滑動
    private float targetHorizontalPosition=0;
    private bool isDraging = false;
    public Toggle[] togglegroup;
    // Use this for initialization
    void Start ()
    {

        scrollRect = GetComponent<ScrollRect>();
	}
	
	// Update is called once per frame
	void Update ()
    {
        if(isDraging==false)
        scrollRect.horizontalNormalizedPosition = Mathf.Lerp(scrollRect.horizontalNormalizedPosition, targetHorizontalPosition, Time.deltaTime*smoothing);
	}
    public void OnBeginDrag(PointerEventData eventData)
    {
        isDraging = true;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        isDraging = false;
        float PosX = scrollRect.horizontalNormalizedPosition;
        int index = 0;
        float offset = Mathf.Abs(pageArray[index] - PosX);

        for(int i=1;i<pageArray.Length;i++)
        {
            float offsetTemp = Mathf.Abs(pageArray[i] - PosX);
            if(offsetTemp<offset)
            {
                index = i;
                offset = offsetTemp;
            }
        }
        targetHorizontalPosition = pageArray[index];
        togglegroup[index].isOn = true;   //下面的選項想匹配
        //scrollRect.horizontalNormalizedPosition = pageArray[index];
    }

    //下面的Toggle也可以控制關卡的滑動
    public void MovePanel1(bool isOn)
    {
        if(isOn)
        {
            targetHorizontalPosition = pageArray[0];
        }
    }

    public void MovePanel2(bool isOn)
    {
        if (isOn)
        {
            targetHorizontalPosition = pageArray[1];
        }
    }

    public void MovePanel3(bool isOn)
    {
        if (isOn)
        {
            targetHorizontalPosition = pageArray[2];
        }
    }

    public void MovePanel4(bool isOn)
    {
        if (isOn)
        {
            targetHorizontalPosition = pageArray[3];
        }
    }
}

利用Layout:Grid Layout Group 和 Vertical Layout Group要新增一個空物體,把要排序的物體放入空物體下,中心保持一致