学习这篇文章的前提是:1.使用了FairyGUI 2.使用了lua
直接上源码,原理没什么,看代码能懂,可根据实际项目需求修改。
注册UI监听事件
function Main_MainUI:_constructor(pMainView)
--pMainView表示该UI实例
pMainView.onTouchBegin:Add(self.OnTouchBegin,self);
pMainView.onTouchMove:Add(self.OnTouchMove,self);
pMainView.onTouchEnd:Add(self.OnTouchEnd,self);
end
--摇杆
function Main_MainUI:OnTouchBegin(eventContext)
if self.touchId == -1 then
--设置摇杆位置
local evt = eventContext.data;
self.touchId = evt.touchId;
local pt = FairyGUI.GRoot.inst:GlobalToLocal(Vector2.New(evt.x, evt.y));
local bx = pt.x
local by = pt.y
if bx<0 then
bx = 0
elseif bx>self.btn_openjoy.width then
bx = self.btn_openjoy.width
end
if by>FairyGUI.GRoot.inst.height then
by = FairyGUI.GRoot.inst.height
elseif by<self.btn_openjoy.y then
by = self.btn_openjoy.y
end
self._lastStageX = bx;
self._lastStageY = by;
self._startStageX = bx;
self._startStageY = by;
self.img_joybg.x = bx - self.img_joybg.width/2
self.img_joybg.y = by - self.img_joybg.height/2
self.img_joy.x = bx - self.img_joy.width/2
self.img_joy.y = by - self.img_joy.height/2
self.ShowJoy.selectedIndex = 0
eventContext:CaptureTouch()
end
end
function Main_MainUI:OnTouchMove(eventContext)
local evt = eventContext.data;
if self.touchId~= -1 and evt.touchId == self.touchId then
local pt = FairyGUI.GRoot.inst:GlobalToLocal(Vector2.New(evt.x, evt.y));
local bx = pt.x
local by = pt.y
local moveX = bx - self._lastStageX
local moveY = by -self._lastStageY
self._lastStageX = bx
self._lastStageY = by
local buttonX = self.img_joy.x+moveX
local buttonY = self.img_joy.y+moveY
local offsetX = buttonX + self.img_joy.width / 2 - self._startStageX;
local offsetY = buttonY + self.img_joy.height / 2 - self._startStageY;
local rad = Mathf.Atan2(offsetY, offsetX);
local degree = rad * 180 / Mathf.PI -90
local maxX = self.radius * Mathf.Cos(rad);
local maxY = self.radius * Mathf.Sin(rad);
if (Mathf.Abs(offsetX) > Mathf.Abs(maxX)) then
offsetX = maxX
end
if (Mathf.Abs(offsetY) > Mathf.Abs(maxY)) then
offsetY = maxY
end
buttonX = self._startStageX + offsetX;
buttonY = self._startStageY + offsetY;
if buttonX < 0 then
buttonX = 0
end
if buttonY > FairyGUI.GRoot.inst.height then
buttonY =FairyGUI.GRoot.inst.height
end
self.img_joy:SetXY(buttonX - self.img_joy.width / 2, buttonY - self.img_joy.height / 2);
end
end
function Main_MainUI:OnTouchEnd()
self.touchId = -1
self.ShowJoy.selectedIndex = 1
end
UI中的结构
self.ShowJoy为显隐控制器