Unity中的关卡滑动

关卡滑动最主要的是ScrollRect组件里的属性horizontalNormalizedPosition(页面水平滑动的值)和vertiacalNormalizedPosition(页面垂直滑动的值);这里我的项目是水平滑动。
 

horizontalNormalizedPosition的最小值是0,最大值是1;也就是说你的第一页是0,最后一页是1;这里需要注意的是如果你有四页,第二页不是0.25,需要你自己测试(就是程序在第二页的时候,去打印一下horizontalNormalizedposition就可以了)。

现在就开始我的项目:如果看项目文件,加我qq:23353677;

public class ScrollPage : MonoBehaviour,IBeginDragHandler,IEndDragHandler {
 
//滑动组件
public ScrollRect scrollRect;
 
//每一页滚动区域的定位坐标
public float[] posArr = new float[] { 0, 0.3333f, 0.666f, 1 };
 
//页码索引
public int pageIndex = 0;
 
//目标位置
public float targetPos;
 
//是否拖拽
public bool isDrag;
 
//单选按钮组
List toggles;
 
void Start () {
scrollRect = GetComponent();
toggles = new List();
this.GetComponentsInChildren(toggles);
//给每个单选按钮添加时间
foreach (var item in toggles) {
item.onValueChanged.AddListener(delegate(bool flag) {
//因为点击单选按钮时 会有两个按钮触发事件,所以要判断
if (flag) {
//把名字中的字母替换掉,只留数字,然后转化成int类型作为下标;
int index = int.Parse(item.name.Replace("p",""));
//更新目标位置
targetPos = posArr[index];
pageIndex = index;
}
});
}
}
 
void Update () {
if (!isDrag)
{
scrollRect.horizontalNormalizedPosition = Mathf.Lerp(scrollRect.horizontalNormalizedPosition,targetPos,Time.deltaTime*5);
}
}
 
public void OnBeginDrag(PointerEventData eventData)
{
isDrag = true;
}
 
public void OnEndDrag(PointerEventData eventData)
{
isDrag = false;
/*第一种方法
 
float curPos = scrollRect.horizontalNormalizedPosition;
//鼠标(滑条的水平值scrollRect.horizontalNormalizedPosition)和每个页码的距离最小,就去哪一页
//offset最小距离,先假设第一页和鼠标的距离差;
pageIndex = 0;
float offset = Mathf.Abs(curPos - posArr[pageIndex]);
for (int i = 1; i < posArr.Length; i++) {
float temp = Mathf.Abs(curPos - posArr[i]);
if(temp < offset)
{
offset = temp;
pageIndex = i;
}
}
//更新目标位置
targetPos = posArr[pageIndex];
//单选按钮为真
toggles[pageIndex].isOn = true;
 
*/
 
 
//第二种方法
 
float curPos = scrollRect.horizontalNormalizedPosition;
//根据当前和原始的位置差,是正是负,判断向左向右
//如果当前和原始的位置差小于一个值,就不改变当前的页码了
if (Mathf.Abs(curPos - targetPos) < 0.07f) { return; }
//正值右滑
if (curPos - targetPos > 0)
{
pageIndex = pageIndex + 1 > posArr.Length - 1 ? posArr.Length - 1 : pageIndex+1;
Debug.Log(pageIndex);
}
else {
pageIndex = pageIndex - 1 < 0 ? 0 : pageIndex-1;
}
 
targetPos = posArr[pageIndex];
toggles[pageIndex].isOn = true;
 
}
}

你可能感兴趣的:(Unity)