好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Unity UGUI教程之实现滑页效果

简介

项目需要...直接展示效果吧:

原理

使用ugui提供的scrollrect和scrollbar组件实现基本滑动以及自己控制每次移动一页来达到滑页的效果。

实现过程

1.创建两个panel,上面的panel用于显示,下面的panel用于存放按钮

2.在toppanel上添加scrollrect脚本,用于滑动

3.在toppanel下创建一个新的panel,并在子panel下拜访要显示的对象

4.将该子panel设置为scrollrect的活动对象

5.为scrollrect添加scrollbar滚动条,直接在空白处单机右键添加scrollbar即可

6.将scrollbar与scrollrect关联

7.设置scrollrect的其他参数

8.将slidercontrol脚本挂在toppanel上,并关联scrollbar

9.添加响应事件

为按钮也添加相应的事件(记住是五个按钮哈)

10.运行查看效果吧,如果出错,请检查上述步骤

代码

?

slidercontrol:

using unityengine;

using system.collections;

using unityengine.ui;

public class slidercontrol : monobehaviour

{

public scrollbar m_scrollbar;

public scrollrect m_scrollrect;

private float mtargetvalue;

private bool mneedmove = false ;

private const float move_speed = 1f;

private const float smooth_time = 0.2f;

private float mmovespeed = 0f;

public void onpointerdown()

{

mneedmove = false ;

}

public void onpointerup()

{

// 判断当前位于哪个区间,设置自动滑动至的位置

if (m_scrollbar.value <= 0.125f)

{

mtargetvalue = 0;

}

else if (m_scrollbar.value <= 0.375f)

{

mtargetvalue = 0.25f;

}

else if (m_scrollbar.value <= 0.625f)

{

mtargetvalue = 0.5f;

}

else if (m_scrollbar.value <= 0.875f)

{

mtargetvalue = 0.75f;

}

else

{

mtargetvalue = 1f;

}

mneedmove = true ;

mmovespeed = 0;

}

public void onbuttonclick(int value)

{

switch (value)

{

case 1:

mtargetvalue = 0;

break ;

case 2:

mtargetvalue = 0.25f;

break ;

case 3:

mtargetvalue = 0.5f;

break ;

case 4:

mtargetvalue = 0.75f;

break ;

case 5:

mtargetvalue = 1f;

break ;

default :

debug.logerror( "!!!!!" );

break ;

}

mneedmove = true ;

}

void update()

{

if (mneedmove)

{

if (mathf.abs(m_scrollbar.value - mtargetvalue) < 0.01f)

{

m_scrollbar.value = mtargetvalue;

mneedmove = false ;

return ;

}

m_scrollbar.value = mathf.smoothdamp(m_scrollbar.value, mtargetvalue, ref mmovespeed, smooth_time);

}

}

}

总结

移动用的mathf提供的平滑函数,如果需要阻尼效果,可以自己修改代码。

以上内容是小编给大家介绍的unity ugui教程之实现滑页效果,希望对大家有所帮助!

dy("nrwz");

查看更多关于Unity UGUI教程之实现滑页效果的详细内容...

  阅读:39次