这是我写的第二篇,因为吃了大亏,解决问题后尽快记录,希望可以帮助到你。
项目需求是这样的 从英雄列表中点击头像,再拖动到指定地点,中间会有预制体的生成。到达目标点后,重新生成预设并播放动画声音。这些需求暂不讨论,咱们先讲讲拖拽问题。
先上c#端的代码
IBeginDragHandler,IEndDragHandler,IDragHandler
先继承接口
private Action<PointerEventData> _onPointerDragStart;
private Action<PointerEventData> _onPointerDragEnd;
private Action<PointerEventData> _onPointerDrag;
Get("onMouseDragStart", out _onPointerDragStart);
Get("onMouseDragEnd", out _onPointerDragEnd);
Get("onMouseDrag", out _onPointerDrag);
实现接口
void IBeginDragHandler.OnBeginDrag(PointerEventData eventData)
{
if (_onPointerDragStart != null)
{
_onPointerDragStart(eventData);
}
}
void IDragHandler.OnDrag(PointerEventData eventData)
{
if (_onPointerDrag != null)
{
_onPointerDrag(eventData);
}
}
void IEndDragHandler.OnEndDrag(PointerEventData eventData)
{
if (_onPointerDragEnd != null)
{
_onPointerDragEnd(eventData);
}
}
直接操作ui,所以这里只是牵扯到屏幕坐标转为ugui坐标,比较简单
我使用的EventSystem,因为需求正好需要按下,拖动中,抬起这三个动作,所以用到了三个接口
其次贴下坐标转换吧,方便齐全不用找
这个是屏幕坐标转ui坐标
public Vector2 ScreenToUGUIPosition(RectTransform transform,Vector2 ScreenPos)
{
Vector2 pos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(transform, ScreenPos, UICamera, out pos);
return pos;
}
再然后就是我经历的坑了,也是我经验不够,所以才有这篇博客
我之前是直接将生成物体的rectTransform传入坐标转换中,发现会物体拖拽时会抖动
经过百般查找都没有找到一个所以然,在万分无奈下尝试将生成物体的父物体也就是自身的传入
(这里也就是self_rect)解决问题
function onMouseDragStart()
if click_image.enabled then
is_down = true
texture = assetManager:LoadPrefab('ui/TeamSetForm/RenderTexture')
self_rect = self.transform:GetComponent('RectTransform')
rect_texture =texture.transform:GetComponent('RectTransform')
texture.transform:SetParent(self.transform, false)
local mouse_pos = UE.Input.mousePosition
local position = UE.Vector2(mouse_pos.x, mouse_pos.y)
local pos = uiMgr:ScreenToUGUIPosition(self_rect,position)
rect_texture.anchoredPosition = pos
end
end
function onMouseDrag(event_data)
if rect_texture ~= nil then
local event_pos = event_data.position
local pos = UE.Vector2(event_pos.x, event_pos.y)
local new_pos = uiMgr:ScreenToUGUIPosition(self_rect,pos)
rect_texture.anchoredPosition = new_pos
end
end
function onMouseDragEnd()
if texture ~= nil then
is_down = false
rect_texture = nil
click_image.enabled = false
end
end
踩完坑(解决完bug之后)没有去完善优化代码,而是直接跑到这里记录下来,完全是因为担心明天忘记。
所以请看的大佬看这几段代码时不要皱眉,能帮你解决问题才是我所希望
还望各位在看的时候指出不足,感谢各位大佬。