1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
|
local CtrlLayer = class('CtrlLayer', function() return display.newLayer('CtrlLayer') end)
local btn_dir_w = 265 local btn_dir_h = 265
local btn_dir_x = display.width - btn_dir_w - 20 local btn_dir_y = 20
local btn_dir_cx = btn_dir_x + btn_dir_w/2 local btn_dir_cy = btn_dir_y + btn_dir_h/2
local btn_dir_center_r = 50
function CtrlLayer:ctor(linstener)
self.linstener = linstener
self:pos(0, 0) self:size(display.width, display.height)
local dirSprite = display.newSprite('dir_btn.jpg') dirSprite:setAnchorPoint(0, 0) dirSprite:pos(btn_dir_x, btn_dir_y) dirSprite:addTo(self)
self:setTouchEnabled(true) self:setTouchMode(cc.TOUCHES_ONE_BY_ONE) self:addNodeEventListener(cc.NODE_TOUCH_EVENT, function(event) if event.name == 'began' then return true elseif event.name == 'ended' then self:onTouchEnded(event) end end)
end
function CtrlLayer:isInDirBtn(x, y) if x >= btn_dir_x and x <= (btn_dir_x + btn_dir_w) and y >= btn_dir_y and y <= (btn_dir_y + btn_dir_h) then return true else return false end end
function CtrlLayer:isInDirBtnCenter(x, y) local tx = math.abs(x-btn_dir_cx) local ty = math.abs(y-btn_dir_cy) local tlen = math.sqrt( math.pow(tx, 2) + math.pow(ty, 2) ) return tlen <= btn_dir_center_r end
function CtrlLayer:getDir(x, y) local dir = '' local tx = math.abs(x - btn_dir_cx) local ty = math.abs(y - btn_dir_cy) if x > btn_dir_cx then if y > btn_dir_cy then if tx > ty then dir = 'right' else dir = 'up' end else if tx > ty then dir = 'right' else dir = 'down' end end else if y > btn_dir_cy then if tx > ty then dir = 'left' else dir = 'up' end else if tx > ty then dir = 'left' else dir = 'down' end end end return dir end
function CtrlLayer:onTouchEnded(event) local x, y = event.x, event.y if self:isInDirBtn(x, y) then if not self:isInDirBtnCenter(x, y) then local dir = self:getDir(x, y) self.linstener:setDir(dir) end end end
return CtrlLayer
|