UI系统——HW8
-
UI效果制作:制作一个Scroll View 选择板
-
首先在GameObeject->UI->Scroll View创建一个Scroll View,创建的Scroll View会有水平滚动条与竖直滚动条,因为是横向选择板,所以需要删除竖直滚动条,并且在Scroll View中的Scroll Rect设置为None。
-
-
在Scroll View的Content中添加Grid Layout Group组件,实现网格布局,设置每一个cell的大小,并调节Content到合适的位置。在Content下添加12张图片,并为每张图片设置相应的标题。
效果如下:
-
在Scroll View添加一个Panel作为中心框,并且调整透明度以及添加一个边框。Panel的边框是用一张黑色的图片制作的,Image Type设置为Sliced,不勾选Fill Center。
效果如下:
-
在Scroll View底部添加一个Toggle,勾选Toggle才显示中心框。
-
设置背景。
-
中心框需要计算当前的中心位置,在CenterOnChild中实现此功能:在游戏运行一开始,获得滚动框的长度,然后根据每个子物体的宽度和间隔,计算出每个子物体分别在中心位置时的x轴坐标。在中心框出现且滑动或滚动结束后,找出里中心点最近的子物体,并且将该子物体移动到之前计算好的位置。
public void OnEndDrag(PointerEventData eventData)
{
//拖动结束,需要移到中心位置
centering = true;
drag = false;
//找到最近的目标位置
targetPos = FindClosestPos(container.localPosition.x);
}
public void OnDrag(PointerEventData eventData)
{
//拖动中
drag = true;
centering = false;
}
public void ScrollbarDrag()
{
//不是直接拖动滑动框里面的内容
if(!drag)
{
centering = true;
targetPos = FindClosestPos(container.localPosition.x);
}
}
private float FindClosestPos(float currentPos)
{
float closest = 0;
float distance = Mathf.Infinity;
for (int i = 0; i < childrenPos.Count; i++)
{
float pos = childrenPos[i];
float dis = Mathf.Abs(pos - currentPos);
//找寻距离当前位置最近的子物体中心位置
if (dis < distance)
{
distance = dis;
closest = pos;
}
}
//返回需要移动到最近的位置
return closest;
}
public void CheckToggle()
{
check = !check;
if(check)
{
//当选中时需要将最近的一个子物体移到中心框里
centering = true;
targetPos = FindClosestPos(container.localPosition.x);
//中心框显示
panel.SetActive(true);
}
else
{
panel.SetActive(false);
}
}
-
选中整个框体结构,可以随鼠标移动,在DragMove中,获得鼠标按下点的坐标,使它转化为UI界面的坐标,设置选中框体的位置为鼠标的位置。
public void OnBeginDrag(PointerEventData eventData)
{
SetPosition(eventData);
}
public void OnDrag(PointerEventData eventData)
{
SetPosition(eventData);
}
public void OnEndDrag(PointerEventData eventData)
{
SetPosition(eventData);
}
private void SetPosition(PointerEventData eventData)
{
var rectTransform = gameObject.GetComponent<RectTransform>();
Vector3 globalMousePos;
//将屏幕空间点转换为位于给定RectTransform平面上的世界空间中的位置
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rectTransform, eventData.position, eventData.pressEventCamera, out globalMousePos))
{
rectTransform.position = globalMousePos;
}
}
-
将CenterOnChild脚本挂载到Scroll View上,将DragMove脚本挂在到想要随鼠标移动的UI上。