local MainScene= class("MainScene",function ( ) return cc.Scene:create(); end)
function MainScene:create( ) -- self.scene = cc.Scene:create() self.scene =MainScene.new() self.scene:addChild(MainScene:createLayer()) return self.scene; end
function MainScene:createLayer() self.layer = cc.Layer:create()
local function onNodeEvent( event ) if "enter"==event then self:onEnter() elseif "exit"==event then self:onExit() end
end
--注册layer的 进入 退出事件用法 self.layer:registerScriptHandler(onNodeEvent)
--蚂蚁容器 self.Antvessel={} --背景图 local bg=cc.Sprite:create("22.png") bg:setPosition(cc.p(display.cx,display.cy)) bg:setContentSize(cc.size(480,320)); self.layer:addChild(bg)
--触摸 self.layer:onTouch(function( event ) if event.name=="began" then print(event.x,event.y)
return true elseif event.name=="moved" then print("moved") elseif event.name=="ended" then print("ended") --遍历是否碰撞 for k,v in pairs(self.Antvessel) do print(k,v) local p = cc.p(event.x,event.y) local rect = v:getBoundingBox() if cc.rectContainsPoint(rect,p) then --删除父节点 v:removeFromParent() --从表(容器)删除 table.remove(self.Antvessel,k) print("出蚂蚁数目" ..#self.Antvessel) end end
end
end)
return self.layer end
function MainScene:startAnimate() -- -蚂蚁动画 --加载到精灵帧缓存 display.loadSpriteFrames("ant.plist","33.png") print("蚂蚁============================") --时间计度器 self.antShareScheduler =self.scene:getScheduler() -- 或 --self.antShareScheduler = cc.Director:getInstance():getScheduler() self.antScheduID = self.antShareScheduler:scheduleScriptFunc(function() --接收一个os.time()作为随即序列的种子。 :scheduleScriptFunc math.randomseed(os.time()) -- math.random([n [,m]]) print("蚂蚁--------------------------------------") -- 用法:1.无参调用,产生[0, 1)之间的浮点随机数。
-- 2.一个参数n,产生[1, n]之间的整数。
-- 3.两个参数,产生[n, m]之间的整数。 antNum = math.random(6)--[1, n] self.butterfly =display.newSprite("#ants" ..antNum .."_1.png",antNum*80-40,50) table.insert(self.Antvessel, self.butterfly)
print("入蚂蚁数目" ..#self.Antvessel) -- self.butterfly:setScale(2) self.layer:addChild(self.butterfly)
-- 创建精灵祯动画 local frames =display.newFrames("ants" ..antNum .."_%d.png",1,3) local animation =display.newAnimation(frames,0.1) self.butterfly:playAnimationForever(animation) local moveto1=cc.MoveBy:create(3 ,cc.p(0,320))
seq= cc.Sequence: create(moveto1) self.butterfly: runAction(seq)
--超出屏幕删除 for k,v in pairs(self.Antvessel) do print(k,v) local x,y = v:getPosition() if y>320 then --删除父节点 v:removeFromParent() --从表(容器)删除 table.remove(self.Antvessel,k) print("出蚂蚁数目" ..#self.Antvessel) end end
end, 1, false) end
function MainScene:onEnter( ) print("我是onEnter") self:startAnimate() end
function MainScene:onExit( ) print("我是onExit") self.antSharedScheduler:unscheduleScriptEntry(self.antScheduID) end
return MainScene
|
请发表评论