需要实现的功能:
- 处理触屏事件,生成移动数据
--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)endfunction 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)endfunction JoyRocker:touchmoved( event ) -- body --print("touch moved") self:refreshRocker(event.x,event.y)endfunction 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)endfunction 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) endendreturn JoyRocker
使用:
JoyRocker:new():align(display.CENTER,display.cy):addTo(self)总结
以上是内存溢出为你收集整理的quick实现虚拟摇杆全部内容,希望文章能够帮你解决quick实现虚拟摇杆所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)