Unity中的关卡滑动

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

 

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<Toggle> toggles;
void Start () {
scrollRect = GetComponent<ScrollRect>();
toggles = new List<Toggle>();
this.GetComponentsInChildren<Toggle>(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;
}
}
  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值