function ControlLayer:createDir( )
--加入摇杆背景
self.dirBg = display.newSprite("#joyStick.png")
self:addChild(self.dirBg)
self.dirBg:setPosition(self.dirBg:getContentSize().width*0.5 + 20,
self.dirBg:getContentSize().height*0.5 + 20)
--摇杆球
self.dir = display.newSprite("#joyStickCenter.png")
self.dirBg:addChild(self.dir)
self.orginPoint = cc.p(self.dirBg:getContentSize().width*0.5, self.dirBg:getContentSize().height*0.5)
self.dir:setPosition(self.orginPoint)
self.dir:setTouchEnabled(true)
-- 添加touch事件
self.dir:addNodeEventListener(cc.NODE_TOUCH_EVENT, function ( event )
return self:onDirTouch(event)
end)
end
--搖桿的touch事件
function ControlLayer:onDirTouch( _event)
if _event.name == "began" then
self.startPoint = cc.p(_event.x, _event.y)
return true
elseif _event.name == "moved" then
local R = self.dirBg:getContentSize().width*0.5
local r = self.dir:getContentSize().width*0.5
local dt = R - r
local distance = math.sqrt(math.pow((_event.x - self.startPoint.x), 2) +
math.pow((_event.y - self.startPoint.y), 2))
--圈外
if distance > dt then
--1.拿到方向
local vec = cc.pSub(cc.p(_event.x, _event.y), self.orginPoint)
--2.方向单位化
local normalize = cc.pNormalize(vec)
--3 距离
local length = cc.pMul(normalize, dt)
--4 安装到原点
local pos = cc.pAdd(length, self.orginPoint)
self.dir:setPosition( pos)
else -- 圈里
self.dir:setPosition(self.dirBg:convertToNodeSpace(cc.p(_event.x, _event.y)))
end
elseif _event.name == "ended" then
self.dir:setPosition(self.orginPoint)
end
end
--加入摇杆背景
self.dirBg = display.newSprite("#joyStick.png")
self:addChild(self.dirBg)
self.dirBg:setPosition(self.dirBg:getContentSize().width*0.5 + 20,
self.dirBg:getContentSize().height*0.5 + 20)
--摇杆球
self.dir = display.newSprite("#joyStickCenter.png")
self.dirBg:addChild(self.dir)
self.orginPoint = cc.p(self.dirBg:getContentSize().width*0.5, self.dirBg:getContentSize().height*0.5)
self.dir:setPosition(self.orginPoint)
self.dir:setTouchEnabled(true)
-- 添加touch事件
self.dir:addNodeEventListener(cc.NODE_TOUCH_EVENT, function ( event )
return self:onDirTouch(event)
end)
end
--搖桿的touch事件
function ControlLayer:onDirTouch( _event)
if _event.name == "began" then
self.startPoint = cc.p(_event.x, _event.y)
return true
elseif _event.name == "moved" then
local R = self.dirBg:getContentSize().width*0.5
local r = self.dir:getContentSize().width*0.5
local dt = R - r
local distance = math.sqrt(math.pow((_event.x - self.startPoint.x), 2) +
math.pow((_event.y - self.startPoint.y), 2))
--圈外
if distance > dt then
--1.拿到方向
local vec = cc.pSub(cc.p(_event.x, _event.y), self.orginPoint)
--2.方向单位化
local normalize = cc.pNormalize(vec)
--3 距离
local length = cc.pMul(normalize, dt)
--4 安装到原点
local pos = cc.pAdd(length, self.orginPoint)
self.dir:setPosition( pos)
else -- 圈里
self.dir:setPosition(self.dirBg:convertToNodeSpace(cc.p(_event.x, _event.y)))
end
elseif _event.name == "ended" then
self.dir:setPosition(self.orginPoint)
end
end