小弟新手一枚,在尝试用cocos2dx-lua做游戏。
在一个scene中原先有一个可触摸的精灵。(一个筷子,它会随着手指移动,当检测到一直向上移动时,设置筷子setTouchEnabled(false),筷子自己向上飞出去,到屏幕顶部停止,print一个语句)它的onTouch函数一直执行正常。
后来在屏幕边上加了一个暂停的精灵,点击,即可暂停。发现筷子的onTouch函数执行不正常了,它会自己短时间连续执行好多次,有的时候一次,有的时候五六次或更多。我可以肯定onTouch函数出问题是新加了一个可触摸精灵的问题。当只是把暂停加进去,而设置它不可触摸,onTouch函数立马变正常了,只执行一次。
还有就是我想实现暂停的功能,把那个精灵换成一个button。同样是这样的问题。
这个问题困扰了我一个星期了,实在不知道哪里有问题。求各位大神帮帮忙吧~~~!!!
--详细代码如下:
local btnpause=display.newSprite("btn/pause.png")
btnpause:align(display.LEFT_TOP,0,display.top)
btnpause:addTo(self)
btnpause:setTouchEnabled(true)
btnpause:setTouchMode(cc.TOUCH_MODE_ONE_BY_ONE)
btnpause:addNodeEventListener(cc.NODE_TOUCH_EVENT, function (event)
print("zanting")
end) - -上面是添加暂停精灵的
stick=display.newSprite("img/chopsticks.png")
:align(display.CENTER, display.cx,-60)
:addTo(self,1)
function onTouch(event)
if event.name=="began" or event.name=="moved" then
local directionY=event.y-event.prevY
local directionX=event.x-event.prevX
local direction=cc.p(directionX,directionY) --以拖动点为锚点移动精灵。注意getPostion返回值为x,y,不是cc.p
local locationX,locationY=stick:getPosition()
local location=cc.p(locationX,locationY)
local stickHeight=stick:getContentSize().height
stick:setPosition(cc.pAdd(location,cc.p(directionX,directionY))) --实现方法:精灵原先的位置+手指移动的位移向量=现在的位置
if directionY>1 then --向上拖动,筷子飞出去前使触摸失效
stick:setTouchEnabled(false)
directionY=0
local schedulerUp=cc.Director:getInstance():getScheduler() --设置一个计时器使筷子向上移动
local schedulerUpID=nil
schedulerUpID=schedulerUp:scheduleScriptFunc(function()
locationY=locationY+100
if locationY+stickHeight/2>display.top then --筷子到达顶部时停止计时器。。onTouch函数会执行好几次。结果就是print多此
scheduler.unscheduleGlobal(schedulerUpID)
print("到头了")
end
stick:setPositionY(locationY)
end,0,false)
end
end
return true
end