JoyRocker(虚拟摇杆)的quick实现
--JoyRocker.lua
--[[ 虚拟摇杆: 通过触屏事件传出数据 ]]
local JoyRocker = class("JoyRocker",function ()
-- body
return display.newLayer()
end)
function JoyRocker:ctor()
-- body
self.rocker_radius = 50.0
self.rodker_vec = cc.p(0,0)
self:initUI()
self:initTouch()
print(self.rocker_vec)
end
--初始化点击事件
function JoyRocker:initTouch()
-- body
self:setTouchEnabled(true)
self:addNodeEventListener(cc.NODE_TOUCH_EVENT,function(event)
--printf("touch:%s Pos:(%0.2f,%0.2f)",event.name,event.x,event.y)
if event.name == "began" then
--todo
self:touchBegan(event)
return true
elseif event.name == "moved" then
--todo
self:touchMoved(event)
elseif event.name == "ended" then
--todo
self:touchEnded(event)
end
end)
end
function JoyRocker:initUI()
-- body
self.rockerBg = display.newSprite("joy_rocker_bg.png"):align(display.CENTER,display.cx,display.cy):addTo(self)
self.rocker = display.newSprite("joy_rocker.png"):align(display.CENTER,display.cy):addTo(self)
self:hideRocker()
end
--[[ 点击事件的回调函数 ]]
function JoyRocker:touchBegan(event)
-- body
--print("touch began")
self:showRocker(event.x,event.y)
end
function JoyRocker:touchMoved( event )
-- body
--print("touch moved")
self:refreshRocker(event.x,event.y)
end
function JoyRocker:touchEnded( event )
-- body
--print("touch ended")
self:hideRocker()
end
--[[ 显示摇杆 ]]
function JoyRocker:showRocker(x,y)
-- body
self.rockerBg:setVisible(true)
self.rocker:setVisible(true)
self.rockerBg:setPosition(x,y)
self.rocker:setPosition(x,y)
end
--[[ 隐藏摇杆 ]]
function JoyRocker:hideRocker()
-- body
self.rockerBg:setVisible(false)
self.rocker:setVisible(false)
self.rockerBg:setPosition(display.cx,display.cy)
self.rocker:setPosition(display.cx,display.cy)
end
function JoyRocker:refreshRocker(x,y)
-- body
local bg_x = self.rockerBg:getPositionX()
local bg_y = self.rockerBg:getPositionY()
if cc.pGetDistance(cc.p(bg_x,bg_y),cc.p(x,y)) <= self.rocker_radius then
--todo
self.rocker:setPosition(x,y)
else
--todo
local dis = cc.pGetDistance(cc.p(bg_x,y))
local a = self.rocker_radius
local b = dis - a
local c = math.abs(y - bg_y)
local d = a * c /(a + b)
local e = math.sqrt(a^2-d^2)
local aim_x = 0.0
local aim_y = 0.0
if bg_x == x or bg_y == y then
--todo
if bg_x == x then
--todo
aim_x = bg_x
aim_y = y > bg_y and bg_y + self.rocker_radius or bg_y - self.rocker_radius
elseif bg_y == y then
--todo
aim_x = x > bg_x and bg_x + self.rocker_radius or bg_x - self.rocker_radius
aim_y = bg_y
end
else
--todo
if x > bg_x and y > bg_y then
--第一象限
aim_x = bg_x + e
aim_y = bg_y + d
elseif x < bg_x and y > bg_y then
--第二象限
aim_x = bg_x - e
aim_y = bg_y + d
elseif x < bg_x and y < bg_y then
--第三象限
aim_x = bg_x - e
aim_y = bg_y - d
elseif x > bg_x and y < bg_y then
--第四象限
aim_x = bg_x + e
aim_y = bg_y - d
end
end
self.rocker:setPosition(aim_x,aim_y)
end
end
return JoyRocker
使用:
JoyRocker:new():align(display.CENTER,display.cy):addTo(self)