最近学习,碰到个移动滑杆控制操作的代码,写的不错,在这里和大家分享一下
UI:
首先用UGUI创建个滑杆
public class TouchDrag : MonoBehavIoUr, IDragHandler,IPointerDownHandler,IPointerUpHandler
{
public Transform touchPoint;
public Transform touchBg;
private Vector2 startPos;
private float pointdis;//滑杆半径
private void Update()
{
//这一步是为了解决滑杆半径可能会随屏幕变化而改变的自适应操作
//我的前面文章也有类似的介绍
pointdis = Screen.height * 1.0f /
Constants.ScreenStandardHeight * Constants.Screenopdis;
}
public void OnDrag(PointerEventData eventData)
{
//半径长度
Vector2 r = eventData.position-(Vector2)touchBg.position;
float len = r.magnitude;
//中心点是否超过滑杆半径
//超过则做出限制
if(len>pointdis)
{
r = Vector2.ClampMagnitude(r, pointdis);
touchPoint.position = (Vector2)touchBg.position + r;
}
else
{
//没有超出圆盘,正常赋值触碰位置
touchPoint.position = eventData.position;
}
}
public void OnPointerDown(PointerEventData eventData)
{
/* 这里可以看出eventData.position的坐标和Input.mousePosition是相同的
Debug.Log("Evenpos: " + eventData.position);
Debug.Log("Mousepos: " + Input.mousePosition);
*/
startPos = touchBg.position;
touchBg.position = eventData.position;
}
public void OnPointerUp(PointerEventData eventData)
{
//结束 将圆盘归位
touchPoint.localPosition = Vector3.zero;
touchBg.position = startPos;
}
}
上述代码已给出详细注释。自适应那里,如果是按一定分辨率播放的话,可以不做处理直接赋值半径长度即可。 主要是拖拽时的处理让人头凉,这种处理应该还不错。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。