--[[ Packaging_KernelEngine.h 文件说明:所有对象在建立时位置是优先的,传入位置参数必须cc.p(X,Y) CurObj:表示要传入当前的对象 将3.10 lua api 放到 C:UsersAdministratorDocumentsBabeLuaCompletion ***************]] -- Valid Line Number 2901 -- local Obj = require("cocos.Packaging_Kernel") local PackagingClass = class("PackagingClass"); -- 精灵 PackagingClass.m_Sprites = { }; PackagingClass.m_SpritesPosition = { }; PackagingClass.m_SpritesWidthAndHeight = { }; -- 纹理 PackagingClass.m_Texture2D = { }; -- 粒子 PackagingClass.m_ParticleEffects = { }; -- 遮罩 PackagingClass.m_MaskTier = { }; -- 骨骼动画 PackagingClass.m_SkeletonAnimation = { }; -- 颜色层 PackagingClass.m_LayerColor = { }; -- UIButton PackagingClass.m_Button = { }; PackagingClass.m_ButtonPosition = { }; PackagingClass.m_ButtonWidthAndHeight = { }; -- Music PackagingClass.m_Music = { }; -- Font PackagingClass.m_Font = { }; -- 回调函数无参动作 PackagingClass.m_CallBackFunctionAction = { }; -- 延时动作 PackagingClass.m_DelayAction = { }; -- 连接动作 PackagingClass.m_ConnectAction = { }; -- 创建多个同时执行动作 PackagingClass.m_Spawn = { }; -- 创建一个让多个同时执行的连接动作重复动作 次数 PackagingClass.m_Repeat = { }; -- 无限动作 PackagingClass.m_InfiniteAction = { }; -- 创建一个动作移动到另一个地方再返回 PackagingClass.m_MoveToLineage = { }; -- 创建一个动作移动到另一个地方是否返回 PackagingClass.m_MoveToInfernal = { }; -- 创建一个闪烁动作 PackagingClass.m_BlinkAction = { }; -- 创建一个几秒钟内消失的动作 PackagingClass.m_SecondVanish = { }; -- 创建一个几秒钟内出现的动作 PackagingClass.m_SecondAppear = { }; -- 创建一个跳的动作(To) PackagingClass.m_JumpTo = { }; -- 创建一个跳的动作(By) PackagingClass.m_JumpBy = { }; -- 创建一个旋转动作(To) PackagingClass.m_RotateTo = { }; -- 创建一个旋转动作(By) PackagingClass.m_RotateBy = { }; -- 创建一个贝塞尔曲线动作(To)(By用的是相对坐标) PackagingClass.m_BezierAction = { }; -- =====================================3D动作 -- 创建一个3D旋转动作 PackagingClass.m_OrbitCamera = { }; -- 创建一个3D翻页动作 PackagingClass.m_PageTurn3D = { }; -- 创建一个3D扭曲动作 PackagingClass.m_Twirl = { }; -- =========================================功能性 -- 创建一个ScrollView 容器 PackagingClass.m_Scrollview = { }; PackagingClass.m_Position = { }; -- 构造函数 function PackagingClass:ctor() print("=======================packaing Call") end -- ======================================================精灵 -- 创建精灵 function PackagingClass:CreateSprite(FilePathName) self.m_Sprites = cc.Sprite:create(FilePathName); self.m_Sprites:setPosition(cc.p(0, 0)); return self.m_Sprites; end -- 设置精灵坐标 function PackagingClass:SetSpritePosition(Position) self.m_Sprites:setPosition(Position); end -- 返回精灵当前的坐标 function PackagingClass:GetSpritePosition() self.m_SpritesPosition.X, self.m_SpritesPosition.Y = self.m_Sprites:getPosition(); return self.m_SpritesPosition; end -- 返回精灵当前的宽高 function PackagingClass:GetSpriteWidthAndHeight() self.m_SpritesWidthAndHeight.Width = self.m_Sprites:getContentSize().width; self.m_SpritesWidthAndHeight.Height = self.m_Sprites:getContentSize().height; return self.m_SpritesWidthAndHeight; end -- 创建一张纹理 function PackagingClass:CreateTexture2D(FilePathName) local Texture = cc.TextureCache:getInstance():addImage(FilePathName); self.m_Texture2D = Texture; return Texture; end -- 用纹理创建一个精灵 function PackagingClass:CreateTextureSprite(Texture) local Sprite = cc.Sprite:createWithTexture(Texture); self.m_Sprites = Sprite; return Sprite; end -- 设置精灵的比例 -- 比例按百分比,在设置中源比例是1.0,及100%100源图片,填入=》精灵,cc.p(X的比例,Y的比例) -- 值得注意的是设置节点的比例,相对于XY轴也会改变,最好就设置精灵的比例就可以了 function PackagingClass:SetSpriteScale(Sprites, Scale) Sprites:setScaleX(Scale.x); Sprites:setScaleY(Scale.y); end -- 创建一个颜色层 function PackagingClass:CreateLayerColor() local LayerColor = cc.LayerColor:create(cc.c3b(0, 0, 0)) LayerColor:setOpacity(200) LayerColor:setName("UnityBackgroundColorLayer") self.m_LayerColor = LayerColor; return LayerColor; end -- ======================================================粒子 --[[//CCParticleExplosion //爆炸粒子特效 -- // CCParticleFire //火焰粒子特效 -- // CCParticleFlower //花束粒子特效 -- // CCParticleFireworks //烟花粒子特效 -- // CCParticleGalaxy //星系粒子特效 -- // CCParticleMeteor //流星粒子特效 -- // CCParticleRain //下雨粒子特效 -- // CCParticleSmoke //烟雾粒子特效 -- // CCParticleSnow //下雪粒子特效 -- // CCParticleSpiral //漩涡粒子特效 --// CCParticleSun //太阳粒子特效]] -- 烟花粒子=》文件路径,粒子数量,角度 function PackagingClass:Create_Base_ParticleEffects_Fireworks(FilePathName, Position, ParticleNumber, StartSize, EndSize, StartColor, EndColor, Speed, LifeCycle) self.m_ParticleEffects = cc.ParticleFireworks:createWithTotalParticles(ParticleNumber); self.m_ParticleEffects:retain(); self.m_ParticleEffects:setAngleVar(180); self.m_ParticleEffects:setGravity(cc.p(0, 0)); -- self.m_ParticleEffects:setSpeedVar(20); self.m_ParticleEffects:setSpeed(Speed); -- 生存周期-1为永久 self.m_ParticleEffects:setDuration(LifeCycle); self.m_ParticleEffects:setStartSize(StartSize); self.m_ParticleEffects:setEndSize(EndSize); self.m_ParticleEffects:setStartColor(StartColor); self.m_ParticleEffects:setEndColor(EndColor); self.m_ParticleEffects:setTexture(cc.TextureCache:sharedTextureCache():addImage(FilePathName)); self.m_ParticleEffects:setPosition(Position); return self.m_ParticleEffects; end -- 烟花粒子=》文件路径,粒子数量,开始颜色,结束颜色,速度,生存周期,重力, function PackagingClass:Create_Base_ParticleEffects_Fireworks2(FilePathName, Position, ParticleNumber, StartSize, EndSize, StartColor, EndColor, Speed, LifeCycle, Gravity_CCP) self.m_ParticleEffects = cc.ParticleFireworks:createWithTotalParticles(ParticleNumber); self.m_ParticleEffects:retain(); self.m_ParticleEffects:setAngleVar(180); self.m_ParticleEffects:setGravity(Gravity_CCP); -- self.m_ParticleEffects:setSpeedVar(20); self.m_ParticleEffects:setSpeed(Speed); -- 生存周期-1为永久 self.m_ParticleEffects:setDuration(LifeCycle); self.m_ParticleEffects:setStartSize(StartSize); self.m_ParticleEffects:setEndSize(EndSize); self.m_ParticleEffects:setStartColor(StartColor); self.m_ParticleEffects:setEndColor(EndColor); self.m_ParticleEffects:setTexture(cc.TextureCache:sharedTextureCache():addImage(FilePathName)); self.m_ParticleEffects:setPosition(Position); return self.m_ParticleEffects; end -- 点击效果烟花粒子=》文件路径,位置,粒子数量 function PackagingClass:Create_Ok_ParticleEffects_Fireworks(ImageName, Position, ParticleNumber) self.m_ParticleEffects = self:Create_Base_ParticleEffects_Fireworks(ImageName, Position, ParticleNumber, 20.0, 1.0, cc.c4b(0, 0, 255, 255), cc.c4b(255, 0, 255, 255), 50, 0.5); return self.m_ParticleEffects; end -- 爆炸粒子特效===>文件路径名,位置,粒子数量,角度,重力,速度,开始的大小,结束的大小,粒子生存时间,开始的颜色,结束的颜色 -- 参数参考===》Obj:Create_ParticleExplosion_Effects("ParticleSystem\guangdian.png",cc.p(appdf.WIDTH / 2 + 9.86, appdf.HEIGHT / 2 + 20.35),100,180,cc.p(0,-100),90,20.0,10.0, 1.0,cc.c4b(255, 255, 0, 255),cc.c4b(255, 255, 255, 255)) function PackagingClass:Create_ParticleExplosion_Effects(FilePathName, Position, Number, Angle, Gravity_CCP, Speed, StartSize, EndSize, Time, StartColor, EndColor) self.m_ParticleEffects = cc.ParticleExplosion:createWithTotalParticles(Number); self.m_ParticleEffects:retain(); self.m_ParticleEffects:setAngleVar(Angle); self.m_ParticleEffects:setGravity(Gravity_CCP); self.m_ParticleEffects:setSpeed(Speed); -- 生存周期-1为永久 self.m_ParticleEffects:setDuration(Time); self.m_ParticleEffects:setStartSize(StartSize); self.m_ParticleEffects:setEndSize(EndSize); self.m_ParticleEffects:setStartColor(StartColor); self.m_ParticleEffects:setEndColor(EndColor); self.m_ParticleEffects:setTexture(cc.TextureCache:sharedTextureCache():addImage(FilePathName)); self.m_ParticleEffects:setPosition(Position); return self.m_ParticleEffects; end -- 加载plist粒子文件 function PackagingClass:LoadPlistPariticle(FilePathName) return cc.ParticleSystemQuad:create(FilePathName); end -- ======================================================遮罩 -- 在模板中设置坐标有问题时,可把模板精灵的坐标先设置,遮罩层的坐标就不用设置了 -- 创建遮罩层=》模板路径,特效路径,模板坐标,特效坐标 function PackagingClass:CreateMaskTier(Template_FilePathName, EffectsFilepathName, Template_Position, Effects_Position) local Template = cc.Sprite:create(Template_FilePathName); local Effects = cc.Sprite:create(EffectsFilepathName); Template:setPosition(Template_Position); Effects:setPosition(Effects_Position); local MaskTier = cc.ClippingNode:create(); MaskTier:setAlphaThreshold(0.5); MaskTier:setInverted(false); MaskTier:addChild(Effects); MaskTier:setStencil(Template); self.m_MaskTier = MaskTier; return MaskTier; end -- 创建遮罩层=》模板路径,特效精灵,模板坐标,特效坐标 function PackagingClass:CreateMaskTier2(Template_FilePathName, EffectsSprite, Template_Position, Effects_Position) local Template = cc.Sprite:create(Template_FilePathName); Template:setPosition(Template_Position); EffectsSprite:setPosition(Effects_Position); local MaskTier = cc.ClippingNode:create(); MaskTier:setAlphaThreshold(0.5); MaskTier:setInverted(false); MaskTier:addChild(EffectsSprite); MaskTier:setStencil(Template); self.m_MaskTier = MaskTier; return MaskTier; end -- 创建遮罩层=》模板精灵,特效精灵,模板坐标,特效坐标=====》支持 function PackagingClass:CreateMaskTier3(Template_Sprite, EffectsSprite, Template_Position, Effects_Position) Template_Sprite:setPosition(Template_Position); EffectsSprite:setPosition(Effects_Position); local MaskTier = cc.ClippingNode:create(); MaskTier:setAlphaThreshold(0.5); MaskTier:setInverted(false); MaskTier:addChild(EffectsSprite); MaskTier:setStencil(Template_Sprite); self.m_MaskTier = MaskTier; return MaskTier; end -- 创建遮罩层=》模板精灵,特效路径,模板坐标,特效坐标=====>返回模板节点,和模板精灵(进度条专用) -- 特效精灵路径=>可以用进度条中的内容,用于显示真的内容 function PackagingClass:CreateMaskTier4(Template_Sprite, EffectsFilepathSprite, Template_Position, Effects_Position) local EffectsSprite = Obj:CreateSprite(EffectsFilepathSprite); Template_Sprite:setPosition(Template_Position); EffectsSprite:setPosition(Effects_Position); local MaskTier = cc.ClippingNode:create(); MaskTier:setAlphaThreshold(0.5); MaskTier:setInverted(false); MaskTier:addChild(EffectsSprite); MaskTier:setStencil(Template_Sprite); self.m_MaskTier = MaskTier; return MaskTier; end -- ======================================================骨骼动画加载 -- 创建骨骼动画=>.json+.stlas一个文件夹下,位置,速度json动画索引 -- Ctrl + H 把json中的skinnedmesh替换为mesh function PackagingClass:CreateSkeletonAnimation(FilePathName_Json, FilePathName_Atlas, Position, TimeSpeed, BOOL, JsonIndex) -- 在json中,如果失败改一个类型 local SkeletonAnimation = sp.SkeletonAnimation:create(FilePathName_Json, FilePathName_Atlas); SkeletonAnimation:setPosition(Position); SkeletonAnimation:setTimeScale(TimeSpeed); -- json中的默认动画 SkeletonAnimation:setAnimation(0, JsonIndex, BOOL); self.m_SkeletonAnimation = SkeletonAnimation; return SkeletonAnimation; end -- 创建骨骼"OR"动画=>.csb+.png一个文件夹下,当前对象,大小比例,速度 function PackagingClass:CreateSkeletonAnimation2(FilePathName, Position, CurObj, SizeScale, TimeSpeed, BOOL) if (CurObj == nil) then return false; end local this = CurObj; local CsbNode = cc.CSLoader:createNode(FilePathName); CsbNode:setPosition(Position) CsbNode:setScale(SizeScale) local Start_Action = cc.CSLoader:createTimeline(FilePathName); Start_Action:setTimeSpeed(TimeSpeed); CsbNode:runAction(Start_Action); Start_Action:gotoFrameAndPlay(0, BOOL); this:addChild(CsbNode); return CsbNode; end -- 创建骨骼"OR"动画=>.csb+.png一个文件夹下,当前对象,大小比例,速度 function PackagingClass:CreateSkeletonAnimation3(FilePathName, Position, SizeScale, TimeSpeed, BOOL) local CsbNode = cc.CSLoader:createNode(FilePathName); CsbNode:setPosition(Position) CsbNode:setScale(SizeScale) local Start_Action = cc.CSLoader:createTimeline(FilePathName); Start_Action:setTimeSpeed(TimeSpeed); CsbNode:runAction(Start_Action); Start_Action:gotoFrameAndPlay(0, BOOL); -- 直接返回节点 return CsbNode; end -- 获取节点的子对象,也可能是子节点 -- 不能获取节点中的宽高,坐标也不可能是绝对坐标,而绝对坐标是加载csb所设置的坐标,所有子节点的坐标都是基于加载csb所设置的坐标 function PackagingClass:GetChildObj(NodeRootObj, ObjName) -- 如果返回的是节点二不是对象,则继续getChildByName("") local NodeObj = NodeRootObj:getChildByName(ObjName); if (NodeObj == nil) then -- 当前节点下没有此对象 return false; else return NodeObj, true; end -- 相反则是removeChildByName(""); end -- ======================================================帧动画动画加载 --[[文件加载路径:卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍 加载csb时,是把res文件下作为主搜索路径,在加载csb文件时,csb项目文件是和res主搜索路径相对的 --如果csb在项目中在一个文件夹下,那res中就必须有这个文件夹,否则断言 --如果csb在项目中没在一个文件夹下,那必须放这res中,如果放在其他文件夹下了,则加载时写下全路径, --如果隔了两个父文件及以上,需要添加搜索路径,否则失败 --最好把发布的资源直接扔在res下,以发布出来的文件为主 --在加载csb中的子对象时,不用再self:addChild()==>因为在加载csb整个文件是已经做了 --卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍卍]] -- 帧动画 .plist+.png一个文件夹下,位置,当前对象,总共图片,plist中图片key -- local Animation = Obj:CreateFrameAnimation("AnimationTest/EffectPlist.plist", cc.p(display.center), self, 总共多少张, "Effect/0/%d.png") function PackagingClass:CreateFrameAnimation(FilePathName, Position, CurObj, EndFrame, XmlImageName) if (CurObj == nil) then return false; end local cache = cc.SpriteFrameCache:getInstance(); cache:addSpriteFrames(FilePathName); local Test = cc.Sprite:create(); -- WithSpriteFrameName("image/boss_spider-angry_0.png") Test:setPosition(Position); local animation = cc.Animation:create(); for i = 0, EndFrame do local bing = cache:getSpriteFrame(string.format(XmlImageName, i)); animation:addSpriteFrame(bing); end -- 设置单位延迟 animation:setDelayPerUnit(0.1); animation:setRestoreOriginalFrame(true); local action = cc.Animate:create(animation); Test:runAction(cc.RepeatForever:create(action)); CurObj:addChild(Test); end -- 帧动画 .plist+.png一个文件夹下,.png,位置,当前对象,开始图片_0,结束图片_N,总共图片.plist中图片key function PackagingClass:CreateFrameAnimation2(FilePathName, Position, CurObj, StartFrame, EndFrame, XmlImageName) if (CurObj == nil) then return false; end local pshowFrame = cc.Sprite:createWithSpriteFrameName(FilePathName); pshowFrame:setPosition(Position); local animation = cc.Animation:create(); for i = StartFrame, EndFrame do local szName = string.format(XmlImageName, i); local pSpriteFrame = cc.SpriteFrameCache:getInstance():getSpriteFrame(szName); animation:addSpriteFrame(pSpriteFrame); end animation:setDelayPerUnit(0.1); animation:setRestoreOriginalFrame(true); local action = cc.Animate:create(animation); pshowFrame:runAction(cc.RepeatForever:create(action)); -- CurObj:addChild(pshowFrame); return pshowFrame; end -- ======================================================UI按钮 --按钮解决方案 -- addTouchEventListener( function(sender, tType)end)--触摸回调 --[[ ccui.TouchEventType = { began = 0, moved = 1, ended = 2, canceled = 3, } ]] -- sender:getTouchMovePosition() --获取触摸移动位置 -- touch:getTouchBeganPosition() --获取触摸开始位置 -- ... -- 创建一个普通按钮=>抬起,按下,禁用,位置,当前对象,回调函数 function PackagingClass:CreateUIButton(UpFileImageName, DownFileImageName, ProhibitFileImageName, Position, CurObj, CallBack) if (CurObj == nil) then return false; end local Button = ccui.Button:create(); Button:loadTextureNormal(UpFileImageName); Button:loadTexturePressed(DownFileImageName); Button:loadTextureDisabled(ProhibitFileImageName); Button:setPressedActionEnabled(false); -- Button:setOpacity(100);--透明度,0为完全透明 Button:setPosition(Position); if (CallBack == nil) then -- 没有传回调函数默认加一个 Button:addClickEventListener( function() end); else Button:addClickEventListener(CallBack); end self.m_Button = Button; CurObj:addChild(Button); return Button; end -- 创建一个可调比例按钮=>抬起,按下,禁用,位置,设置UI大小,当前对象,回调函数 function PackagingClass:CreateUIButton2(UpFileImageName, DownFileImageName, ProhibitFileImageName, Position, ContenSize, CurObj, CallBack) if (CurObj == nil) then return false; end local Button = ccui.Button:create(); Button:loadTextureNormal(UpFileImageName); Button:loadTexturePressed(DownFileImageName); Button:loadTextureDisabled(ProhibitFileImageName); Button:setPressedActionEnabled(false); Button:setScale9Enabled(true); ------- -- Button:setOpacity(100);--透明度,0为完全透明 if (ContenSize.x) and(ContenSize.y) then Button:setContentSize(ContenSize.x, ContenSize.y); else Button:setContentSize(ContenSize.width, ContenSize.height); end ------ Button:setPosition(Position); if (CallBack == nil) then -- 没有传回调函数默认加一个 Button:addClickEventListener( function() end); else Button:addClickEventListener(CallBack); end self.m_Button = Button; CurObj:addChild(Button); return Button; end -- 返回当前UI的位置 function PackagingClass:GetCurUIPosition() self.m_ButtonPosition.X = self.m_Button:getPositionX(); self.m_ButtonPosition.Y = self.m_Button:getPositionY(); return self.m_ButtonPosition; end -- 返回当前UI的宽高 function PackagingClass:GetUIWidthAndHeight() self.m_ButtonWidthAndHeight.Width = self.m_Button:getContentSize().width; self.m_ButtonWidthAndHeight.Height = self.m_Button:getContentSize().height; return self.m_ButtonWidthAndHeight; end -- ======================================================动作 -- 一个动作只能给一个对象用,当第二个对象用是这个动作可以当层已经是个NULL了 -- To By 区别,By多一个成员函数reverse, 这个支持方向动作reverse(颠倒) ,及(cc.p(200,200)) ==>(cc.p(-200,-200)) -- To 不支持一直无限执行 -- 创建回调函数(无参)=》动作 function PackagingClass:CreateCallBackFunction(Function) local CallBackFunction = cc.CallFunc:create(Function); self.m_CallBackFunctionAction = CallBackFunction; return CallBackFunction; end -- 创建延时动作 function PackagingClass:CreateDelayAction(Time) local DelayActionTime = cc.DelayTime:create(Time); self.m_DelayAction = DelayActionTime; return DelayActionTime; end -- 创建连接动作(一个一个执行) function PackagingClass:CreateConnectAction(...) local Sequence = cc.Sequence:create(...); self.m_ConnectAction = Sequence; return Sequence; end -- 创建多个动作同时执行的连接动作 -- 同时执行的动作只能由固定次数的动作执行 function PackagingClass:CreateMultiMeanwhileAction(...) local Spawn = cc.Spawn:create(...); self.m_Spawn = Spawn; return Spawn; end -- 创建一个让多个同时执行的连接动作重复动作 次数 function PackagingClass:CreateMultiMeanwhileAction(Action, ActionNumber) local Repeat = cc.Repeat:create(Action, ActionNumber); self.m_Repeat = Repeat; return Repeat; end -- 创建无限动作 function PackagingClass:CreateInfiniteAction(Action) local InfiniteAction = cc.RepeatForever:create(Action); self.m_InfiniteAction = InfiniteAction; return InfiniteAction; end -- 创建动作移动到另一个地方并返回 function PackagingClass:CreateMoveToLineageAction(Position_Start, Position_End, StarTime, EndTime) local MoveAction_Start = cc.MoveTo:create(StarTime, Position_Start); local MoveAction_End = cc.MoveTo:create(EndTime, Position_End); local MoveToLineage = self:CreateConnectAction(MoveAction_Start, MoveAction_End); self.m_MoveToLineage = MoveToLineage; return MoveToLineage; end -- 创建动作移动到另一个地方是否返回 function PackagingClass:CreateMoveToInfernalAction(Position_Start, BOOL, Position_End, StarTime, EndTime) if (BOOL == true) then local MoveAction_Start = cc.MoveTo:create(StarTime, Position_Start); local MoveAction_End = cc.MoveTo:create(EndTime, Position_End); local MoveToLineage = self:CreateConnectAction(MoveAction_Start, MoveAction_End); self.m_MoveToLineage = MoveToLineage; return MoveToLineage; else local MoveAction_Infernal = cc.MoveTo:create(StarTime, Position_Start); self.m_MoveToInfernal = MoveAction_Infernal; return MoveAction_Infernal; end end -- 创建动作移动到另一个地方 function PackagingClass:CreateMoveToWorld(Position_End, EndTime) local MoveAction_Infernal = cc.MoveTo:create(EndTime, Position_End); self.m_MoveToInfernal = MoveAction_Infernal; return MoveAction_Infernal; end -- 创建一个闪烁动作=》多少秒,多少次 执行完了恢复正常 function PackagingClass:CreateBlinkAction(Time, TimeNumber) local BlinkAction = cc.Blink:create(Time, TimeNumber); self.m_BlinkAction = BlinkAction; return BlinkAction; end -- 创建一个几秒钟内消失的动作 function PackagingClass:CreateSecondVanishAction(Time) local SecondVanish = cc.FadeOut:create(Time); self.m_SecondVanish = SecondVanish; return SecondVanish; end -- 创建一个几秒钟内出现的动作 function PackagingClass:CreateSecondAppearAction(Time) local SecondAppear = cc.FadeIn:create(Time); self.m_SecondAppear = SecondAppear; return SecondAppear; end -- 创建一个跳的动作(To) function PackagingClass:CreateJumpToAction(Time, Position, Height, Number) local JumpTo = cc.JumpTo:create(Time, Position, Height, Number); self.m_JumpTo = JumpTo; return JumpTo; end -- 创建一个跳的动作(By) function PackagingClass:CreateJumpByAction(Time, Position, Height, Number) local JumpBy = cc.JumpBy:create(Time, Position, Height, Number); self.m_JumpBy = JumpBy; return JumpBy; end -- 创建一个旋转的动作(To) function PackagingClass:CreateRotateToAction(Time, Angle) local RotateTo = cc.RotateTo:create(Time, Angle); self.m_RotateTo = RotateTo; return RotateTo; end -- 创建一个旋转的动作(By) function PackagingClass:CreateRotateByAction(Time, Angle) local RotateBy = cc.RotateBy:create(Time, Angle); self.m_RotateBy = RotateBy; return RotateBy; end -- 创建一个贝塞尔曲线动作(To)(By用的是相对坐标) function PackagingClass:CreateBezierToAction(Time, BezierConfig) local BezierAction = cc.BezierTo:create(Time, BezierConfig); self.m_BezierAction = BezierAction; return BezierAction; end -- 创建一个贝塞尔曲线动作(To)(By用的是相对坐标)==>时间,开始的点,弯曲的顶点(控制的点),结束的点 function PackagingClass:CreateBezierToAction2(Time, StartPoint, CurveVertex, EndPoint) local BezierConfig = { StartPoint, CurveVertex, EndPoint }; local BezierAction = cc.BezierTo:create(Time, BezierConfig); self.m_BezierAction = BezierAction; return BezierAction; end -- ======================================================3D动作 -- 3D动作说明:由于没有设置波动要持续多久,则返回的有些是无限的3D动作 -- 深度缓冲区只能开启一次,当前函数可以直接掉,不用开启OpenGL的深度缓冲区 -- 除了 Create3DRotateAction()函数可以混合使用外,其他用NodeGrid运行的不能混合使用,如果把NodeGrid运行动作 -- 代码放到非NodeGrid运行的回调里会卡顿和其他的未知问题 -- 创建3D动作环境=>精灵条件(精灵必须没有在任何一个节点上,比如csb的精灵就不行) function PackagingClass:Create3DAction(CurObj, Sprites) local NodeGrid = cc.NodeGrid:create(); NodeGrid:addChild(Sprites); CurObj:addChild(NodeGrid); return NodeGrid; end -- 创建3D动作环境=>精灵条件(精灵必须没有在任何一个节点上,比如csb的精灵就不行) function PackagingClass:Create3DAction2(Sprites) local NodeGrid = cc.NodeGrid:create(); NodeGrid:addChild(Sprites); return NodeGrid; end -- 创建一个3D旋转动作==》旋转时间,起始半径(1),半径差(0),起始Z角(0),旋转Z角差(360),起始X角(0),旋转X角差(0) -- 此函数的返回值 精灵可以直接运行的动作(runAction()) function PackagingClass:Create3DRotateAction(Time, Start_R, R_SUB, Start_Z, Rotate_Z_SUB, Start_X, Rotate_X) local OrbitCamera = cc.OrbitCamera:create(Time, Start_R, R_SUB, Start_Z, Rotate_Z_SUB, Start_X, Rotate_X); self.m_OrbitCamera = OrbitCamera; return OrbitCamera; end -- 创建一个无限波浪动作==》时间,晃动网格大小,波动速度,振幅率,是否水平波动,是否垂直波动 -- 参数参考实例====Obj:Create3DWavesAction(5,cc.size(10,10),10,20,true,true) function PackagingClass:Create3DWavesAction(Time, ReseauSize, FluctuateSpeed, Amplitude, IsLevelFluctuate, IsVerticalFluctuate) local Waves = cc.Waves:create(Time, ReseauSize, FluctuateSpeed, Amplitude, IsLevelFluctuate, IsVerticalFluctuate); Waves = self:CreateInfiniteAction(Waves); return Waves; end -- 创建一个波浪动作==》时间,晃动网格大小,波动速度,振幅率,是否水平波动,是否垂直波动 -- 参数参考实例====Obj:Create3DWavesAction(5,cc.size(10,10),10,20,true,true) function PackagingClass:Create3DWavesAction2(Time, ReseauSize, FluctuateSpeed, Amplitude, IsLevelFluctuate, IsVerticalFluctuate) local Waves = cc.Waves:create(Time, ReseauSize, FluctuateSpeed, Amplitude, IsLevelFluctuate, IsVerticalFluctuate); return Waves; end -- 创建一个3D水波纹动作==》时间,网格大小,坐标,半径,速度,振幅率 -- 参数参考实例=====Obj:Create3DRipple3DAction(5,cc.size(100,100),cc.p(600,300),240,10,6) function PackagingClass:Create3DRipple3DAction(Time, ReseauSize, Position, R, Speed, Amplitude) local Ripple3D = cc.Ripple3D:create(Time, ReseauSize, Position, R, Speed, Amplitude); Ripple3D = self:CreateInfiniteAction(Ripple3D); return Ripple3D; end -- 创建一个液体动作==》时间,网格大小,速度,振幅率 function PackagingClass:Create3DLiquidAction(Time, ReseauSize, Speed, Amplitude) local Liquid = cc.Liquid:create(Time, ReseauSize, Speed, Amplitude); Liquid = self:CreateInfiniteAction(Liquid); return Liquid; end -- 创建一个瓷砖洗牌特效的动作==》时间,网格大小,随机数(随便填) function PackagingClass:Create3DShuffleTilesAction(Time, ReseauSize, Srand) local ShuffleTiles = cc.ShuffleTiles:create(Time, ReseauSize, Srand); return ShuffleTiles; end -- 创建一个分多少列消失的动作==》时间,多少列 function PackagingClass:Create3DSplitColsAction(Time, Line) local SplitCols = cc.SplitCols:create(Time, Line); return SplitCols; end -- 创建一个3D翻页动作 function PackagingClass:Create3DPageTurnAction(Time, Size) local PageTurn = cc.PageTurn3D:create(Time, Size); self.m_PageTurn3D = PageTurn; return PageTurn; end -- 创建一个扭曲动作 function PackagingClass:Create3DTwirlAction(Time, Size, Position, Twirls, Amplitude) local Twirl = cc.Twirl:create(Time, Size, Position, Twirls, Amplitude); self.m_Twirl = Twirl; return Twirl; end -- ======================================================单点触控 -- CurObj 任何的对象 (也可自定义监听对象) -- 重写函数约定 OnTouchBegin(touch, event) ** OnTouchMove(touch, event) ** OnTouchEnd(touch, event) function PackagingClass:CreateTouchEvent(CurObj) if (CurObj == nil) then return false; end local listener = cc.EventListenerTouchOneByOne:create(); if (listener == nil) then return false; end -- 给触摸监听函数设置吞没事件,使触摸上面的层的时候事件不会向下传递 listener:setSwallowTouches(true) -- OnTouchBegin(touch, event) ** OnTouchMove(touch, event) ** OnTouchEnd(touch, event) local function OnTouchBegin(touch, event) if (CurObj.OnTouchBegin == nil) then return false; end CurObj:OnTouchBegin(touch, event); return true; end local function OnTouchMove(touch, event) if (CurObj.OnTouchMove == nil) then return false; end CurObj:OnTouchMove(touch, event); end local function OnTouchEnd(touch, event) if (CurObj.OnTouchEnd == nil) then return false; end CurObj:OnTouchEnd(touch, event); end listener:registerScriptHandler(OnTouchBegin, cc.Handler.EVENT_TOUCH_BEGAN); listener:registerScriptHandler(OnTouchMove, cc.Handler.EVENT_TOUCH_MOVED); listener:registerScriptHandler(OnTouchEnd, cc.Handler.EVENT_TOUCH_ENDED); local eventDispatcher = cc.Director:getInstance():getEventDispatcher(); eventDispatcher:addEventListenerWithSceneGraphPriority(listener, CurObj); -- 移除 -- if event == "exit" and nil ~= node.onExit then -- if nil ~= node._listener then -- local eventDispatcher = node:getEventDispatcher() -- eventDispatcher:removeEventListener(node._listener) -- end --[[touch成员函数 getLocation();返回坐标结构体,与实际世界坐标的Y非相反的 getCursorX();//返回屏幕坐标X getCursorY();//返回屏幕坐标Y ]] return true; end -- ======================================================Music -- ccexp.AudioEngine -- cc.SimpleAudioEngine function PackagingClass:CreateMusic() local Music = cc.FileUtils:getInstance(); self.m_Music = Music; end function PackagingClass:PlayMusic(MusicFileName) AudioEngine.playMusic(self.m_Music:fullPathForFilename(MusicFileName), true); end function PackagingClass:PauseMusic(MusicFileName) AudioEngine.pauseMusic(self.m_Music:fullPathForFilename(MusicFileName), true); end -- 程序退出时 function PackagingClass:DestroyMusic() AudioEngine.destroyInstance(); end -- ======================================================鼠标 -- 鼠标移动调用约定 OnMouseDown(event) ** OnMouseUp(event) ** OnMouseMove(event) ** OnMouseScroll(event) function PackagingClass:CreateMouseEvent(CurObj) if (CurObj == nil) then return false; end local Dispatcher = cc.Director:getInstance():getEventDispatcher(); local MouseListener = cc.EventListenerMouse:create(); if (MouseListener == nil) then return false; end -- OnMouseDown(event) ** OnMouseUp(event) ** OnMouseMove(event) ** OnMouseScroll(event) local function OnMouseDown(event) if (CurObj.OnMouseDown == nil) then return false; end CurObj:OnMouseDown(event) return true; end local function OnMouseUp(event) if (CurObj.OnMouseUp == nil) then return false; end CurObj:OnMouseUp(event) return true; end local function OnMouseMove(event) if (CurObj.OnMouseMove == nil) then return false; end CurObj:OnMouseMove(event) return true; end local function OnMouseScroll(event) if (CurObj.OnMouseScroll == nil) then return false; end CurObj:OnMouseScroll(event) return true; end MouseListener:registerScriptHandler(OnMouseDown, cc.Handler.EVENT_MOUSE_DOWN); MouseListener:registerScriptHandler(OnMouseUp, cc.Handler.EVENT_MOUSE_UP); MouseListener:registerScriptHandler(OnMouseMove, cc.Handler.EVENT_MOUSE_MOVE); MouseListener:registerScriptHandler(OnMouseScroll, cc.Handler.EVENT_MOUSE_SCROLL); Dispatcher:addEventListenerWithSceneGraphPriority(MouseListener, CurObj); return true; --[[event成员函数 getLocation();返回坐标结构体,与实际世界坐标的Y是相反的 getMouseButton();返回哪一个键 getCursorX();//返回屏幕坐标X getCursorY();//返回屏幕坐标Y ]] end -- ======================================================鼠标箭头隐藏 -- 隐藏当前视口的鼠标箭头 function PackagingClass:SetMouseConceal(BOOL) if (BOOL == nil) then return false; end local DirectorView = cc.Director:getInstance():getOpenGLView(); DirectorView:setCursorVisible(BOOL); return true; end -- ======================================================键盘按键 function PackagingClass:CreateKeyEvent(CurObj) if (CurObj == nil) then return false; end local function OnKeyPressed(KeyCode, Event) -- 16进制 -- print("OOOOOOOOOOOOOOOOOO"..KeyCode.." O "); end local function OnKeyReleased(KeyCode, Event) -- print("OOOOOOOOOOOOOOOOOO"..KeyCode.." O "); end local Listener = cc.EventListenerKeyboard:create(); Listener:registerScriptHandler(OnKeyPressed, cc.Handler.EVENT_KEYBOARD_PRESSED); Listener:registerScriptHandler(OnKeyReleased, cc.Handler.EVENT_KEYBOARD_RELEASED); cc.Director:getInstance():getEventDispatcher():addEventListenerWithSceneGraphPriority(Listener, CurObj); end -- ======================================================计时器 -- 每一帧调用 -- 函数调用约定1 .Update() Or .GameLogicUpdate() -- 函数调用约定2 .Update(interval) Or .GameLogicUpdate(interval) function PackagingClass:CreateTimer_OneFrame(CurObj) if (CurObj == nil) then return false; end -- 如何类中有Update成员函数 if (CurObj.Updata) then -- CurObj:scheduleUpdateWithPriorityLua(CurObj.Updata, 0); -- 每一帧调用 local function handler(interval) CurObj:Updata(interval); end CurObj:scheduleUpdateWithPriorityLua(handler, 0); return true; else if (CurObj.GameLogicUpdata) then -- 如果类中有GameLogicUpdate成员函数 -- CurObj:scheduleUpdateWithPriorityLua(CurObj.GameLogicUpdata, 0); -- 每一帧调用 local function handler(interval) CurObj:GameLogicUpdata(interval); end CurObj:scheduleUpdateWithPriorityLua(handler, 0); return true; else return false; end end end -- 自定义设置秒数调用 function PackagingClass:CreateTimer_DefineSecond(Second) scheduler = cc.Director:getInstance():getScheduler() -- 根据设置每几秒调用这个函数 local function onTimerCallback(dt) print("调用") end self.schedulerID = scheduler:scheduleScriptFunc( function(dt) onTimerCallback(dt) end , Second, false) -- 删除定时器1 -- if (scheduler ~= nil) then -- scheduler:unscheduleScriptEntry(schedulerID) -- scheduler = nil -- end -- 删除定时器2 建议指数1 -- cc.Director:getInstance():getScheduler():unscheduleScriptEntry(schedulerID) end --[[ 问题就出在“第一个参数”上,LUA的函数一般定义方式是ClassName:funcName(f1,f2,f3...),相当于ClassName.funcName(self,f1,f2,f3...) 因为LUA没有类的概念,所以面向对象时每个函数需要一个额外的self参数来指向调用者,LUA提供了“: ”语法来方便我们定义和调用,但是cocos没有。 于是我们的handler第一个参数就直接被cocos传进来的interval给挤掉了,handler函数,或者叫update函数就找不到调用者了。 ]] -- ======================================================常用功能性 -- 从当前对象中删除一个子对象 function PackagingClass:FunctionRestMoveChild(CurObj, MoveObj) CurObj:removeChild(MoveObj) -- 根据名字删除 removeChildByName(""); end -- 创建字体 function PackagingClass:CreateFonts(Buf, TTFFilePath, Size) Font = cc.Label:createWithTTF(Buf, TTFFilePath, Size); self.m_Font = Font; return Font; end -- 获取当前显示视口的宽高 function PackagingClass:GetVisibleSize() return cc.Director:getInstance():getVisibleSize(); end -- 开启深度测试 function PackagingClass:OpenDepthTest() cc.Director:getInstance():setDepthTest(true); end -- 关闭深度测试 function PackagingClass:CloseDepthTest() cc.Director:getInstance():setDepthTest(false); end -- 深度测试 function PackagingClass:DepthTest(Bool) cc.Director:getInstance():setDepthTest(Bool); end -- 获取当前时间的秒数 function PackagingClass:GetTickCount() return os.time(); end -- 退出当前整个程序 function PackagingClass:Exit(ANY) os.exit(0); end -- 设置精灵的透明度--255为全不透明 function PackagingClass:SetSpritOpacity(Sprites, Value) Sprites:setOpacity(Value); return Sprites; end -- 设置精灵的锚点 function PackagingClass:SetSpriteAnchorPoint(Sprites, Point) Sprites:setAnchorPoint(Point); return Sprites; end -- lua强制类型转换 -- 事例 =>tolua.cast(Sprite1,"Sprite");--虽然获取了并强制转换了类型,但,原有的动画将没有了,完完全全成为你想要的类型 -- 一般从Node:getChildByName("");获取,可以在上个场景没有用的素材中找 function PackagingClass:ForseTransition(GameObject, Type) local TemplateType = tolua.cast(GameObject, Type); return TemplateType; end -- 创建一个ScrollView 容器 视口的宽高, 滚动容器的宽高 (0,0)在坐下角 --[[ listView 容器没有设置滚动容器的成员函数,滚动容器的高,pushback(对象不能是精灵)而决定 ]] -- 有关size的 必须用cc.size() function PackagingClass:CreateScrollView(ViewSize, ContainerSize) local Scrollview = ccui.ScrollView:create(); -- 开启触摸 Scrollview:setTouchEnabled(true); -- 开启反弹 Scrollview:setBounceEnabled(true); Scrollview:setDirection(ccui.ScrollViewDir.vertical); -- scrollView:setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL)--垂直滚动 -- scrollView:setDirection(cc.SCROLLVIEW_DIRECTION_HORIZONTAL)--水平滚动 -- 设置显示视口区域宽高 Scrollview:setContentSize(ViewSize); -- 设置滚动区域宽高 Scrollview:setInnerContainerSize(ContainerSize); -- 设置显示视口的位置 Scrollview:setPosition(cc.p(0, 0)); -- 锚点,故它会忽略锚点的设置,其锚点始终为(0,0) -- Scrollview:setAnchorPoint(cc.p(0, 0)); -- 滚动宽度 Scrollview:setScrollBarWidth(30); -- 滚动条为红色 Scrollview:setScrollBarColor(cc.RED); -- 设置滚动条的位置从角落 -- Scrollview:setScrollBarPositionFromCorner(cc.p(2, 2)); -- 关闭滚动条显示 Scrollview:setScrollBarEnabled(false); -- 设置背景图片 Scrollview:setBackGroundImage("Privatemode/listView_background.png") -- 设置滚动到视口的顶部 时间, bool 表示有衰减效果 Scrollview:scrollToTop(Time, true); -- 设置滚动到视口的底部 时间, bool 表示有衰减效果 Scrollview:scrollToBottom(Time, true); -- 获取滚动容器的坐标 local Position = Scrollview:getInnerContainerPosition(); local function Callback(sender, eventType) if (eventType == ccui.ScrollviewEventType.scrollToBottom) then print("滚动到顶部"); end if (eventType == ccui.ScrollviewEventType.scrollToTop) then print("滚动到底部部"); end end -- 添加触摸事件 Scrollview:addTouchEventListener(Callback); -- 该回调函数将会在视图发生滚动时触发 -- Scrollview:addEventListenerScrollView(target, selector) -- 该回调函数将在滚动事件触发时被调用 Scrollview:addEventListener( function() end); self.m_Scrollview = Scrollview; return Scrollview; end -- 贝塞尔循环出发和返回 function PackagingClass:BezierFor() -- 出发时间 local Var__i = 0; -- 出发后时间 local Var__Time = 0; for i = 0, 5 do local Buf = string.format("LogonScene/ChildPNG/%d.png", i); Arr__[i] = cc.Sprite:create(Buf); Arr__[i]:setPosition(cc.p(appdf.WIDTH / 2 - 151, appdf.HEIGHT / 4 * 3 + 25.17)); -- 先后顺序出发的时间 local DeTiemS = cc.DelayTime:create(Var__i); local BezAcS = cc.BezierTo:create(1, MConRight); local BezAcE = cc.BezierTo:create(1, MConLeft); -- 出发后卡住的时间,再回来 local DeTimeE = cc.DelayTime:create((0.75 - Var__Time) * 2); -- 是先后顺序的回来,卡的时间是出发的时间的++ local DeTimeSPluas = cc.DelayTime:create(i * 0.15); local SeAc = cc.Sequence:create(DeTiemS, BezAcS, DeTimeE, BezAcE, DeTimeSPluas); Arr__[i]:runAction(cc.RepeatForever:create(SeAc)); Var__i = Var__i + 0.15; Var__Time = Var__Time + 0.15; end end function PackagingClass:OverallArrangemet(Number) -- for i = 1, Number do -- self.m_Position[i].X = 0; -- self.m_Position[i].Y = 0; -- end local Arr = { }; for i = 1, Number do Arr[i] = { }; Arr[i].X = 0; Arr[i].Y = 0; end for i = 1, Number do Arr[i].X = i; Arr[i].Y = i + 1; print(Arr[i].X .. " " .. Arr[i].Y) end -- //死的 local Up_Y = 1240; local Down_Y = 280; -- //活的 local DisPlayWidth = 750; local DIsplayHeight = 1335; -- //可调 local Up_YOffset = 100; local Down_YOffset = 100; -- //求得 local Up_Down_AddOffset = 0; Up_Down_AddOffset = Up_Y -(Down_Y +(Up_YOffset + Down_YOffset)); -- //活的 local DisPlayLeftX = 60; local DisPlayRightX = 690; -- //最上面的和最下面的的可放总位置的长度 local RightUp = Up_Y - Up_YOffset; local RightDown = Down_Y + Down_YOffset; local RightUpAddDown = RightUp - RightDown; -- //偶数刚刚好 if (Number % 2 == 0) then -- //中间那一个 local Center =(Number / 2) + 1; -- //右边放的总个数 -- //减去最上面的一个就是右边可以放的总数 local RightCount = Center - 2; -- //右边可以放 if (RightCount ~= 0) then -- //直接放的顶端 Arr[1].X = DisPlayWidth / 2; Arr[1].Y = Up_Y; -- //人数为四个的时候 if (RightCount == 1) then Arr[2].X = DisPlayRightX; Arr[2].Y = RightUp - RightUpAddDown / 2; Arr[Center].X = DisPlayWidth / 2; Arr[Center].Y = Down_Y; Arr[4].X = DisPlayLeftX; Arr[4].Y = RightUp - RightUpAddDown / 2; else -- //人数大于四个的时候 -- //Right local RightOneByOneOffset = RightUpAddDown /(RightCount - 1); for i = 0, RightCount do Arr[i + 2].X = DisPlayRightX; Arr[i + 2].Y = RightUp; RightUp = RightUp - RightOneByOneOffset; end Arr[Center].X = DisPlayWidth / 2; Arr[Center].Y = Down_Y; -- //Left local temp = 2; for i = Center + 1, Number do Arr[i].X = DisPlayLeftX; Arr[i].Y = Arr[i - temp].Y; temp = temp + 2; end end else Arr[1].X = DisPlayWidth / 2; Arr[1].Y = Up_Y; Arr[Center].X = DisPlayWidth / 2; Arr[Center].Y = Down_Y; end for i = 1, Number do print(Arr[i].X .. " " .. Arr[i].Y); end else -- //中间那一个 local Center =(Number + 1) / 2; -- //总数只有三个时,从右边开始只放一个 if (Center - 1 == 1) then Arr[1].X = DisPlayRightX; Arr[1].Y = RightUp - RightUpAddDown / 2; Arr[2].X = DisPlayWidth / 2; Arr[2].Y = Down_Y; Arr[3].X = DisPlayLeftX; Arr[3].Y = Arr[1].Y; else Arr[Center].X = DisPlayWidth / 2; Arr[Center].Y = Down_Y; local SideCount =(Number - 1) / 2; local RightOneByOneOffset = RightUpAddDown /(SideCount - 1); for i = 1, Center - 1 do Arr[i].X = DisPlayRightX; Arr[i].Y = RightUp; RightUp = RightUp - RightOneByOneOffset; end -- //Left local temp = 2; for i = Center + 1, Number do Arr[i].X = DisPlayLeftX; Arr[i].Y = Arr[i - temp].Y; temp = temp + 2; end end end for i = 1, Number do print("PPPPPPP: X = " .. Arr[i].X .. " Y = " .. Arr[i].Y) end return Arr; end -- scrollViewDidScroll(view) -- cellSizeForTableRoom(view, idx) -- tableCellAtIndexRoom(view, idx) -- numberOfCellsInTableViewRoom(view) -- onTouchPanelRankItem(sender,eventType) function PackagingClass:CreateTableView(CurObj, Position) local TableView = cc.TableView:create(cc.size(600, 800)); TableView:setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL); TableView:setPosition(Position); TableView:setVerticalFillOrder(cc.TABLEVIEW_FILL_TOPDOWN); -- TableView:setBounceable(true); -- 设置代理 -- TableView:setDelegate(); --和TableView:registerScriptHandler(handler(CurObj,CurObj.scrollViewDidScroll), cc.SCROLLVIEW_SCRIPT_SCROLL); 一起用 -- 返回宽高函数 TableView:registerScriptHandler(CurObj.cellSizeForTableRoom, cc.TABLECELL_SIZE_FOR_INDEX); -- 返回cell TableView:registerScriptHandler(handler(CurObj, CurObj.tableCellAtIndexRoom), cc.TABLECELL_SIZE_AT_INDEX); -- 返回cell数量 TableView:registerScriptHandler(handler(CurObj, CurObj.numberOfCellsInTableViewRoom), cc.NUMBER_OF_CELLS_IN_TABLEVIEW); CurObj:addChild(TableView); TableView:reloadData(); -- -- 触摸吞噬解决方案 -- local listener = cc.EventListenerTouchOneByOne:create(); -- -- 给触摸监听函数设置吞没事件,使触摸上面的层的时候事件不会向下传递 -- listener:setSwallowTouches(true) -- local function OnTouchBegin(touch, event) -- local X = touch:getLocation().x -- local Y = touch:getLocation().y -- print("X = " .. X .. " Y = " .. Y) -- print(event) -- print("触摸开始") -- return true; -- end -- local function OnTouchMove(touch, event) -- local X = touch:getLocation().x -- local Y = touch:getLocation().y -- print("X = " .. X .. " Y = " .. Y) -- print(event) -- print("触摸移动") -- end -- local function OnTouchEnd(touch, event) -- local X = touch:getLocation().x -- local Y = touch:getLocation().y -- print("X = " .. X .. " Y = " .. Y) -- print(event) -- print("触摸结束") -- end -- listener:registerScriptHandler(OnTouchBegin, cc.Handler.EVENT_TOUCH_BEGAN); -- listener:registerScriptHandler(OnTouchMove, cc.Handler.EVENT_TOUCH_MOVED); -- listener:registerScriptHandler(OnTouchEnd, cc.Handler.EVENT_TOUCH_ENDED); -- local eventDispatcher = cc.Director:getInstance():getEventDispatcher(); -- eventDispatcher:addEventListenerWithSceneGraphPriority(listener, TableView); return TableView; end function PackagingClass:utfstrlen(str) local len = #str; local left = len; local cnt = 0; local arr = { 0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc }; while left ~= 0 do local tmp = string.byte(str, - left); local i = #arr; while arr[i] do if tmp >= arr[i] then left = left - i; break; end i = i - 1; end cnt = cnt + 1; end return cnt; end function PackagingClass:stringLen(string) local lenInByte = #string local byteCount = 1 local i = 1 while (i <= lenInByte) do local curByte = string.byte(string, i) -- 单字节编码 if (curByte > 0 and curByte <= 127) then byteCount = 1 -- 其他的多字节或者是双字节编码 else byteCount = 2 end local char = "" if (byteCount > 1) then char = string.sub(string, i, i + 3 - 1) print("中文字符 " .. char) i = i + 3 else char = string.sub(string, i, i) print("英文字符 " .. char) i = i + 1 end byteCount = 0 end return lenInByte; end -- 注意 : . 的调用 function PackagingClass:stringMaxLenPlusPlus(string, maxLen) if (type(string) ~= "string") then return "非字符串或者字符串为空" elseif (maxLen == 0 or maxLen == nil) then return "字符串长度有误" elseif (string == "" or string == nil) then return "字符串有误" elseif (maxLen == #string or maxLen > #string) then return string end local lenInByte = #string local byteCount = 1 local i = 1 local ConstChar = "" -- while (i <= lenInByte) do -- local curByte = string.byte(string, i) -- -- 单字节编码 -- if (curByte > 0 and curByte <= 127) then -- byteCount = 1 -- -- 其他的多字节或者是双字节编码 -- else -- byteCount = 2 -- end -- local char = "" -- if (byteCount > 1) then -- char = string.sub(string, i, i + 3 - 1) -- print("中文 " .. char) -- i = i + 3 -- else -- char = string.sub(string, i, i) -- print("英文 " .. char) -- i = i + 1 -- end -- byteCount = 0 -- end while (i <= maxLen) do local curByte = string.byte(string, i) -- 单字节编码 if (curByte > 0 and curByte <= 127) then byteCount = 1 -- 其他的多字节或者是双字节编码 else byteCount = 2 end local char = "" if (byteCount > 1) then char = string.sub(string, i, i + 3 - 1) print("中文字符 " .. char) i = i + 3 else char = string.sub(string, i, i) print("英文字符 " .. char) i = i + 1 end -- 不管是什么,都保证截取出来的是最完整的字符串 ConstChar = ConstChar .. char byteCount = 0 end return ConstChar .. "....." end -- 随机数 function PackagingClass:Srandom() math.randomseed(os.time()) -- 范围1到3 local rand = math.random(1, 3) end -- 返回大于这个数的整数 function PackagingClass:GetCeil(Number) print(math.ceil(Number)) end --该功能相当于C功能系统。 --它传递要由操作系统shell执行的命令。 --它返回一个与系统相关的状态代码。 --如果命令不存在,则如果外壳程序可用,则返回非零,否则返回零 function PackagingClass:cmd(command) os.execute(command) end --根据函数名字调用函数 function PackagingClass:strCallFunction(String) -- local str = string.dump(String) -- loadstring(str)() end return PackagingClass; -- cocos-x Engine 中Main --[[ Node:addChild();--参数基本上就能填,只要是个节点(csb)等,对象,精灵,粒子等等等 self:getParent(); --返回当前类的父类的节点 --从父类移除 self:removeFromParent() --把自己从父类移除掉 cc.Show:create();--直接显示动作,无参数 cc.Hide:create();--直接消失动作,无参数 --Scale9Sprite --9宫格精灵 1 2 3 4 5 6 7 8 9 setCapInsets(CCRectMake(0,0,800,600));--从0,0点拉伸多宽, setContentSize(Size::Size(800,600));--最终显示的宽高 --]] --[[ dropdown 列表创建 先需要一个主按钮,其他的用层来存,层的事件再分发给主按钮 ]] --[[ ScrollView 不能添加checkbox 解决方案 用listView self._listView = ccui.ListView:create() self._listView:setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL) self._listView:setBounceEnabled(true) -- 滑动惯性 self._listView:setBackGroundImage("Privatemode/listView_background.png") self._listView:setBackGroundImageScale9Enabled(true) self._listView:setContentSize(viewWidth, viewHeight) self._listView:setPosition(cc.p(viewposX, viewposY)) self._listView:jumpToTop() self:addChild(self._listView) 由于listView 有点局限性 所有这样 self._layerOut = ccui.Layout:create() self._layerOut:setContentSize(viewWidth, 1200) self._listView:pushBackCustomItem(self._layerOut) ]] -- 自定义监听对象 --[[ local listener = cc.EventListenerTouchOneByOne:create(); listener:setSwallowTouches(true) local function OnTouchBegin(touch, event) print("SSSSSSSSSSSSSSSSSSSS " .. touch:getStartLocation().x) print("SSSSSSSSSSSSSSSSSSSS " .. touch:getLocation().x) return false; end listener:registerScriptHandler(OnTouchBegin, cc.Handler.EVENT_TOUCH_BEGAN) local eventDispatcher = cc.Director:getInstance():getEventDispatcher(); eventDispatcher:addEventListenerWithSceneGraphPriority(listener, item); -- local listener = cc.EventListenerTouchOneByOne:create(); -- listener:setSwallowTouches(false) -- local function OnTouchBegin(touch, event) -- print("OnTouchBegin " .. touch:getStartLocation().x) -- print("OnTouchBegin " .. touch:getLocation().x) -- return true; -- end -- local function OnTouchMove(touch, event) -- print("OnTouchMove " .. touch:getStartLocation().x) -- print("OnTouchMove " .. touch:getLocation().x) -- print("itemX "..item:getPositionX()) -- print("itemY "..item:getPositionY()) -- end -- local function OnTouchEnd(touch, event) -- print("OnTouchEnd " .. touch:getStartLocation().x) -- print("OnTouchEnd " .. touch:getLocation().x) -- end -- listener:registerScriptHandler(OnTouchBegin, cc.Handler.EVENT_TOUCH_BEGAN) -- listener:registerScriptHandler(OnTouchMove, cc.Handler.EVENT_TOUCH_MOVED); -- listener:registerScriptHandler(OnTouchEnd, cc.Handler.EVENT_TOUCH_ENDED); -- local eventDispatcher = cc.Director:getInstance():getEventDispatcher(); -- eventDispatcher:addEventListenerWithSceneGraphPriority(listener, item); ]] -- lua字符串扩展 --[[ local tb = {}; for utfChar in string.gmatch(String,"[%z1-127194-244][128-191]*") do table.insert(tb,utfChar) end ]] -- 层穿透解决方案 --[[ self:setTouchEnabled(true) self:registerScriptTouchHandler( function() return true end ) --建议用这个 --穿透解决方案 function ClubRecordInquireLayer:penetrateSolution(class,bool) class:setTouchEnabled(bool) class:registerScriptTouchHandler( function() return bool end ) end ]] -- 层穿透解决方案 --[[ self:registerScriptTouchHandler(function(eventType) return true end) ]] --[[ function RoomLayer:unicode_to_utf8(convertStr) if type(convertStr)~="string" then return convertStr end local resultStr="" local i=1 while true do local num1=string.byte(convertStr,i) local unicode if num1~=nil and string.sub(convertStr,i,i+1)=="\u" then unicode=tonumber("0x"..string.sub(convertStr,i+2,i+5)) i=i+6 elseif num1~=nil then unicode=num1 i=i+1 else break end -- print(unicode) if unicode <= 0x007f then resultStr=resultStr..string.char(bit.band(unicode,0x7f)) elseif unicode >= 0x0080 and unicode <= 0x07ff then resultStr=resultStr..string.char(bit.bor(0xc0,bit.band(bit.rshift(unicode,6),0x1f))) resultStr=resultStr..string.char(bit.bor(0x80,bit.band(unicode,0x3f))) elseif unicode >= 0x0800 and unicode <= 0xffff then resultStr=resultStr..string.char(bit.bor(0xe0,bit.band(bit.rshift(unicode,12),0x0f))) resultStr=resultStr..string.char(bit.bor(0x80,bit.band(bit.rshift(unicode,6),0x3f))) resultStr=resultStr..string.char(bit.bor(0x80,bit.band(unicode,0x3f))) end end resultStr=resultStr..' ' return resultStr end ]] --[[ -- local String = EditBox_1_Layer:getText() -- local S = " "; -- local Len = string.len(String); -- local _R_N_ = " "; -- -- 打到换行的长度 -- if (Len >= 84) then -- local i = 1; -- local j = 84; -- -- 总长 -- local len = Len; -- local loop =(Len / 84) -((Len / 84) % 1); -- while true do -- String = String; -- local s = string.sub(String, i, j) -- S = S .. s .. n -- len = len - j; -- if (len <= 0) then -- break; -- else -- i = j + 1; -- j = j + j; -- if (j > Len) then -- j = Len; -- end -- end -- end -- -- 没有到换行的长度 -- else -- end ]] --[[ 复用性问题解决方案 事件 用sender:getParent():getParent():getIdx() + 1 从而得到这个cell -- self.TableView = cc.TableView:create(cc.size(yl.WIDTH, 420)) -- self.TableView:setDirection(cc.SCROLLVIEW_DIRECTION_HORIZONTAL) -- self.TableView:setPosition(cc.p(0,yl.HEIGHT/2-220)) -- self.TableView:setDelegate() -- self.TableView:addTo(self) -- self.TableView:registerScriptHandler(self.tableCellTouched, cc.TABLECELL_TOUCHED) -- self.TableView:registerScriptHandler(handler(self, self.cellSizeForTable), cc.TABLECELL_SIZE_FOR_INDEX) -- self.TableView:registerScriptHandler(handler(self, self.tableCellAtIndex), cc.TABLECELL_SIZE_AT_INDEX) -- self.TableView:registerScriptHandler(self.numberOfCellsInTableView, cc.NUMBER_OF_CELLS_IN_TABLEVIEW) -- self.TableView:reloadData() ]] -- 编辑框解决方案 --[[ editBox:setPlaceholderFont("Arial", 26) editBox:setFont("Arial", 26) ]] -- "Privatemode/btdownUpdate.png", UI_TEX_TYPE_LOCAL 配对 --[[ --创建编辑框 --宽高,坐标,锚点,名字 function ClubSettingLayer:CreateEditBox(Width, Height, X, Y, AnchorPointX, AnchorPointY, StringName) local EditBox = ccui.EditBox:create(cc.size(Width, Height),"blank.png", UI_TEX_TYPE_PLIST) --local EditBox = ccui.EditBox:create(cc.size(Width, Height),"Privatemode/btdownUpdate.png", UI_TEX_TYPE_LOCAL) EditBox:setAnchorPoint(AnchorPointX, AnchorPointY) EditBox:setPosition(X, Y) EditBox:setFontName("fonts/round_fonts.ttf") EditBox:setPlaceholderFontName("fonts/round_fonts.ttf") EditBox:setPlaceholderFontColor(cc.c3b(212, 221, 255)) EditBox:setFontColor(cc.c3b(212, 221, 255)) EditBox:setFontSize(24) --EditBox:setText(StringName) EditBox:setName(StringName) local function editboxEventHandler(eventType,sender) if (eventType == "began") then print("开始编辑") elseif (eventType == "ended") then print("结束编辑") elseif (eventType == "changed") then print("改变编辑") elseif (eventType == "return") then print("返回编辑") end end EditBox:registerScriptEditBoxHandler(editboxEventHandler) return EditBox end ]] --[[ for i = 1, #self.m_ExpendLableArray do print("选择固定积分" .. self.m_ExpendLableArray[i]:getString()) --返回值为查找到的索引值 local Find = string.find(self.m_ExpendLableArray[i]:getString(), -- 查找的字符串 "%", -- 开始查找的位置 string.len(self.m_ExpendLableArray[i]:getString()), -- true表示关闭"%d"这种格式转义字符,按字符串查找 true) if (Find ~= nil) then print("查找到了字符 %") self.m_ExpendLableArray[i]:setString(""..tonumber(string.sub(self.m_ExpendLableArray[i]:getString(),1, Find - 1)) * 100) print("去掉% 的字符串 "..self.m_ExpendLableArray[i]:getString()) end end ]] --编辑框解决方案 --[[ "text" cc.size( , ) " / .png" 123456789 function ClubSettingLayer:createEditBox(text, size, path, tag) local edlistener = function(eventType, sender) if eventType == "began" then sender:setText("") elseif eventType == "return" then if sender:getText() == "" or sender:getText() == nil then sender:setText("0") end self:onEditEvent(sender:getTag()) end end local editBox = ccui.EditBox:create(size, path) editBox:setAnchorPoint(0, 0.5) editBox:setPlaceholderFont("Arial", 30) editBox:setFont("Arial", 30) editBox:setInputMode(cc.EDITBOX_INPUT_MODE_NUMERIC) editBox:setText(text) editBox:setTag(tag) editBox:registerScriptEditBoxHandler(edlistener) return editBox end ]] --公告解决方案 --[[ --修改名称 EditBox local title = display.newSprite("Club/NoticeSetting.png") :setPosition(cc.p(display.cx - 230,display.cy + 50)) :addTo(layer) local bg = ccui.Scale9Sprite:create("Common/sp_input_bg.png") bg:setScale9Enabled(true) bg:setAnchorPoint(0,1) bg:setContentSize(cc.size(440,120)) bg:setPosition(cc.p(title:getPositionX() + title:getContentSize().width / 2 + 15,title:getPositionY() + 10)) layer:addChild(bg) local editBox = ccui.EditBox:create(cc.size(440,120), "blank.png", UI_TEX_TYPE_PLIST) layer:addChild(editBox) editBox:setPosition(cc.p(title:getPositionX() + title:getContentSize().width / 2 + 15,title:getPositionY() - title:getContentSize().height + 10)) editBox:setAnchorPoint(0, 0.5) editBox:setFont("Arial", 26) editBox:setPlaceholderFontColor(cc.c3b(100,100,100)) editBox:setPlaceHolder("请输入新的公告") editBox:setInputMode(cc.EDITBOX_INPUT_MODE_ANY) editBox:registerScriptEditBoxHandler(function(type,sender) if eventType == "began" then sender:setText("") elseif eventType == "return" then if sender:getText() == "" or sender:getText() == nil then sender:setText("刚刚创建新公告") end end end) ]] -- 解决安卓上的显示双层 -- 编辑框 --[[ -- 创建编辑框 -- 宽高,坐标,锚点,名字 function ClubSettingLayer:CreateEditBox(Width, Height, X, Y, AnchorPointX, AnchorPointY, StringName) local EditBox = ccui.EditBox:create(cc.size(Width, Height), "blank.png", UI_TEX_TYPE_PLIST) -- local EditBox = ccui.EditBox:create(cc.size(Width, Height),"Privatemode/btdownUpdate.png", UI_TEX_TYPE_LOCAL) EditBox:setAnchorPoint(AnchorPointX, AnchorPointY) EditBox:setPosition(X, Y) EditBox:setFontName("fonts/round_fonts.ttf") EditBox:setPlaceholderFontName("fonts/round_fonts.ttf") EditBox:setPlaceholderFontColor(cc.c3b(212, 221, 255)) EditBox:setFontColor(cc.c3b(212, 221, 255)) EditBox:setFontSize(24) EditBox:setInputMode(cc.EDITBOX_INPUT_MODE_NUMERIC) EditBox:setMaxLength(6) -- EditBox:setText(StringName) EditBox:setName(StringName) self.g_m_AudioAffectsState = 0 local function editboxEventHandler(eventType) -- 保证只播放一次 if (self.g_m_AudioAffectsState == 0) then ExternalFun.playClickEffect() self.g_m_AudioAffectsState = 1; end if (eventType == "began") then print("开始编辑") if (EditBox:getName() == "抢庄限制") then self.m_bankerLab:setString("") elseif (EditBox:getName() == "下注限制") then self.m_betLab:setString("") elseif (EditBox:getName() == "准备限制") then self.m_readyLab:setString("") elseif (EditBox:getName() == "第一名消耗") then self.m_firstExpendLab:setString("") elseif (EditBox:getName() == "第二名消耗") then self.m_secondExpendLab:setString("") elseif (EditBox:getName() == "第三名消耗") then self.m_thirdExpendLab:setString("") elseif (EditBox:getName() == "消耗最低起扣") then self.m_lowestExpendLab:setString("") end elseif (eventType == "ended") then print("结束编辑") elseif (eventType == "changed") then -- 逻辑放这在手机平台可能会死循环 print("改变编辑") elseif (eventType == "return") then print("返回编辑") self.g_m_AudioAffectsState = 0 if (EditBox:getName() == "抢庄限制") then print("编辑抢庄限制") if (EditBox:getText() == "") then EditBox:setText("0") end self.m_bankerLab:setString(EditBox:getText()) local TempNumber = tonumber(self.m_bankerLab:getString()) if (TempNumber > 100000) then self.m_bankerLab:setString("100000") showToast(self, "最大只能是100000", 2) end self.m_bankerStr = tonumber(self.m_bankerLab:getString()) elseif (EditBox:getName() == "下注限制") then print("编辑下注限制") if (EditBox:getText() == "") then EditBox:setText("0") end self.m_betLab:setString(EditBox:getText()) local TempNumber = tonumber(self.m_betLab:getString()) if (TempNumber > 100000) then self.m_betLab:setString("100000") showToast(self, "最大只能是100000", 2) end self.m_betStr = tonumber(self.m_betLab:getString()) elseif (EditBox:getName() == "准备限制") then print("编辑准备限制") if (EditBox:getText() == "") then EditBox:setText("0") end self.m_readyLab:setString(EditBox:getText()) local TempNumber = tonumber(self.m_readyLab:getString()) if (TempNumber > 100000) then self.m_readyLab:setString("100000") showToast(self, "最大只能是100000", 2) end self.m_readyStr = tonumber(self.m_readyLab:getString()) elseif (EditBox:getName() == "第一名消耗") then print("第一名消耗") if (EditBox:getText() == "") then EditBox:setText("0") end self.m_firstExpendLab:setString(EditBox:getText()) local TempNumber = tonumber(self.m_firstExpendLab:getString()) if (self.m_ExpendNormIdx == 1) then if (TempNumber > 100000) then self.m_firstExpendLab:setString("100000") showToast(self, "最大只能是100000", 2) end else if (TempNumber > 1000) then self.m_firstExpendLab:setString("1000") showToast(self, "百分比最大只能是1000", 2) end end self.m_firstExpendStr = tonumber(self.m_firstExpendLab:getString()) elseif (EditBox:getName() == "第二名消耗") then print("第二名消耗") if (EditBox:getText() == "") then EditBox:setText("0") end self.m_secondExpendLab:setString(EditBox:getText()) local TempNumber = tonumber(self.m_secondExpendLab:getString()) if (self.m_ExpendNormIdx == 1) then if (TempNumber > 100000) then self.m_secondExpendLab:setString("100000") showToast(self, "最大只能是100000", 2) end else if (TempNumber > 1000) then self.m_secondExpendLab:setString("1000") showToast(self, "百分比最大只能是1000", 2) end end self.m_secondExpendStr = tonumber(self.m_secondExpendLab:getString()) elseif (EditBox:getName() == "第三名消耗") then print("第三名消耗") if (EditBox:getText() == "") then EditBox:setText("0") end self.m_thirdExpendLab:setString(EditBox:getText()) local TempNumber = tonumber(self.m_thirdExpendLab:getString()) if (self.m_ExpendNormIdx == 1) then if (TempNumber > 100000) then self.m_thirdExpendLab:setString("100000") showToast(self, "最大只能是100000", 2) end else if (TempNumber > 1000) then self.m_thirdExpendLab:setString("1000") showToast(self, "百分比最大只能是1000", 2) end end self.m_thirdExpendStr = tonumber(self.m_thirdExpendLab:getString()) elseif (EditBox:getName() == "消耗最低起扣") then print("消耗最低起扣") if (EditBox:getText() == "") then EditBox:setText("0") end self.m_lowestExpendLab:setString(EditBox:getText()) local TempNumber = tonumber(self.m_lowestExpendLab:getString()) if (self.m_ExpendNormIdx == 1) then if (TempNumber > 100000) then self.m_lowestExpendLab:setString("100000") showToast(self, "最大只能是100000", 2) end else if (TempNumber > 1000) then self.m_lowestExpendLab:setString("1000") showToast(self, "百分比最大只能是1000", 2) end end self.m_lowestExpendStr = tonumber(self.m_lowestExpendLab:getString()) end EditBox:setText("") end end EditBox:registerScriptEditBoxHandler(editboxEventHandler) return EditBox end ]] -- 检查框解决方案 --[[ if (self._layerOut:getChildByTag(tag):isSelected() == true) then print("之前没有选择,现在选择了") else print("之前有选择,现在没有选择") end ]] --完整编辑框窗口解决方案 --[[ function ClubRoomLayer:setChangeClubNameWindow(clubName) local layer = display.newLayer(cc.c4b(0,0,0,70)) layer:setTouchEnabled(true) layer:registerScriptTouchHandler(function() return true end) self:addChild(layer) local btnOffsetX = 30 local btnOffsetY = -15 -- 背景图 local bg = ccui.Scale9Sprite:create("bg_common_2.png") bg:setScale9Enabled(true) bg:setPosition(display.center) layer:addChild(bg) --标题 display.newSprite("Title/title_ChangeClubName.png") :setPosition(bg:getPositionX(),display.height * 0.5 + bg:getContentSize().height * 0.5 - 42) :addTo(layer) --关闭按钮 local btn = ccui.Button:create("Button/btn_close.png","Button/btn_close.png") btn:setPosition(bg:getPositionX() + bg:getContentSize().width * 0.5 - 40,display.height * 0.5 + bg:getContentSize().height * 0.5 - 40) btn:addClickEventListener(function(sender) sender:getParent():removeFromParent() end) layer:addChild(btn) --修改名称 EditBox local title = display.newSprite("Club/ChangeClubName.png") :setPosition(cc.p(display.cx - 230,display.cy)) :addTo(layer) local editBox = ccui.EditBox:create(cc.size(440,47), "Common/sp_input_bg.png") layer:addChild(editBox) editBox:setPosition(cc.p(title:getPositionX() + title:getContentSize().width / 2 + 15,title:getPositionY())) editBox:setAnchorPoint(0, 0.5) editBox:setPlaceholderFont("Arial", 26) editBox:setFont("Arial", 26) editBox:setPlaceholderFontColor(cc.c3b(100,100,100)) --占位符 editBox:setPlaceHolder("请输入新的名称") editBox:setInputMode(cc.EDITBOX_INPUT_MODE_ANY) editBox:registerScriptEditBoxHandler(function(type,sender) if type == "began" then sender:setText("") elseif type == "return" then if sender:getText() == "" or sender:getText() == nil then sender:setText("0") end end end) -- 取消 local btn_cancel = ccui.Button:create("Button/btn_cancel_bg.png", "Button/btn_cancel_bg.png") btn_cancel:setPosition(cc.p(appdf.WIDTH * 0.5 - 145 - btnOffsetX, appdf.HEIGHT * 0.5 - 170 + btnOffsetY)) btn_cancel:setPressedActionEnabled(true) btn_cancel:setZoomScale(0.1) layer:addChild(btn_cancel) local img_cancel = cc.Sprite:create("Button/text_cancel.png") img_cancel:setPosition(cc.p(btn_cancel:getPositionX(), btn_cancel:getPositionY())) layer:addChild(img_cancel) btn_cancel:addClickEventListener( function(sender, tType) layer:removeFromParent() end ) -- 确定 local btn_confirm = ccui.Button:create("Button/btn_sure_bg.png", "Button/btn_sure_bg.png") btn_confirm:setPressedActionEnabled(true) btn_confirm:setZoomScale(0.1) btn_confirm:setPosition(cc.p(appdf.WIDTH * 0.5 + 145 + btnOffsetX, appdf.HEIGHT * 0.5 - 170 + btnOffsetY)) layer:addChild(btn_confirm) local img_cancel = cc.Sprite:create("Button/text_sure.png") img_cancel:setPosition(cc.p(btn_confirm:getPositionX(), btn_confirm:getPositionY())) layer:addChild(img_cancel) btn_confirm:addClickEventListener( function(sender, tType) end) end ]] -- 输入编辑框解决方案 --[[ -- 输入框 local titleText = ccui.EditBox:create(cc.size(550, 50), "RoomCard/sp_input.png") titleText:setPosition(cc.p(appdf.WIDTH * 0.5, appdf.HEIGHT * 0.5 + 35)) titleText:setFontName("Arial") titleText:setPlaceholderFontName("Arial") titleText:setInputMode(cc.EDITBOX_INPUT_MODE_NUMERIC) -- 限制输入类型 为数字 titleText:setPlaceholderFontColor(cc.c3b(238, 243, 105)) titleText:setFontColor(cc.c3b(255, 255, 255)) titleText:setFontSize(30) self.layer:addChild(titleText) ]] -- 触摸宏 --[[ type == ccui.TouchEventType.move ]] -- 触摸吞噬解决方案 --[[ local btn_close = ccui.Button:create("", "") btn_close:setAnchorPoint(1, 0.5) btn_close:setPosition() --触摸吞噬解决方案1 btn_close:setSwallowTouches(true) --触摸吞噬解决方案2 btn_close:addTouchEventListener(function(sender, tType) print("BBBBBBBBBBBBB"..tType) if(tType == ccui.TouchEventType.ended)then layer:removeFromParent() end end) self:addChild(btn_close) --触摸吞噬解决方案3 -- local listener = cc.EventListenerTouchOneByOne:create(); -- -- 给触摸监听函数设置吞没事件,使触摸上面的层的时候事件不会向下传递 -- listener:setSwallowTouches(true) -- local function OnTouchBegin(touch, event)return true;end -- local function OnTouchMove(touch, event)end -- local function OnTouchEnd(touch, event)layer:removeFromParent()end -- listener:registerScriptHandler(OnTouchBegin, cc.Handler.EVENT_TOUCH_BEGAN); -- listener:registerScriptHandler(OnTouchMove, cc.Handler.EVENT_TOUCH_MOVED); -- listener:registerScriptHandler(OnTouchEnd, cc.Handler.EVENT_TOUCH_ENDED); -- local eventDispatcher = cc.Director:getInstance():getEventDispatcher(); -- eventDispatcher:addEventListenerWithSceneGraphPriority(listener, btn_close); ]] -- 吞噬解决方案 --[[ -- 注册触摸事件(吞噬层) local listener = cc.EventListenerTouchOneByOne:create() -- 事件监听器逐个触摸 listener:setSwallowTouches(true) -- 吞噬触摸 listener:registerScriptHandler( function(touch, event) -- 做触摸处理... return true -- 返回true时,该层下面的层的触摸事件都会屏蔽掉 end , cc.Handler.EVENT_TOUCH_BEGAN) -- 触摸事件开始 local eventDispatcher = self.layer:getEventDispatcher() -- 得到事件调度器 eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self.layer) -- 添加具有场景图优先级的事件监听器 self:addChild(self.layer) ]] --容器内按钮吞噬解决方案 --非常重要 也是常用的 --[[ local btn = ccui.Button:create("Common/sp_cut_line.png") btn:setPosition(cellWidth * 0.5, cellHeight * 0.5) btn:setScale9Enabled(true) btn:setOpacity(255) btn:setContentSize(cc.size(cellWidth, cellHeight + 2)) btn:addTo(item) btn:setSwallowTouches(false) btn:addClickEventListener(function(sender,type) local curidx = sender:getParent():getParent():getIdx() + 1 print("table "..curidx) print("param "..idx) end) ]] -- 字体 --[[ --cocos 自带的字体 cc.Label:createWithSystemFont("", "Arial", 30) cc.Lable:createWithTTF("","Arial.ttf",24) ]] --label 解决方案 --[[ self._strLabel = cc.Label:createWithSystemFont(str, "Arial", 25) :setAnchorPoint(cc.p(0, 1)) --设置没有空格的换行符 :setLineBreakWithoutSpace(true) :setMaxLineWidth(640) :setPosition(cc.p(40,0)) --对其方式 :setAlignment(cc.TEXT_ALIGNMENT_LEFT) :setTextColor(cc.c4b(255, 255, 255, 255)) :addTo(self._scrollView) self._strLabel:setDimensions(600, len + 500) self._strLabel:setHorizontalAlignment(cc.TEXT_ALIGNMENT_LEFT) self._strLabel:setVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_TOP) ]] -- 遍历 --[[ for Key, Value in ipairs(iterationDistanceY_Space) do if (Value.Key == playCount) then distanceY = Value.Value break end end ]] --从文件读取字符串解决方案 --[[ local str = cc.FileUtils:getInstance():getStringFromFile("public/text_help_" .. tostring(GlobalUserItem.nCurGameKind) .. ".txt") ]] -- csb PageView --[[ 添加页的时候请用layout -- local CsbNode = cc.CSLoader:createNode("Test/Test.csb"); -- CsbNode:setPosition(cc.p(0,0)) -- CsbNode:setScale(1.0) -- local Start_Action = cc.CSLoader:createTimeline("Test/Test.csb"); -- Start_Action:setTimeSpeed(1.0); -- CsbNode:runAction(Start_Action); -- Start_Action:gotoFrameAndPlay(0, true); -- self:addChild(CsbNode) -- local P = CsbNode:getChildByName("PageView_1") -- P:setDirection(cc.SCROLLVIEW_DIRECTION_BOTH) -- P:setScrollBarEnabled(true) -- P:setBounceEnabled(true) ]] -- lable对其方式 --[[ --设置维度 gameRule:setDimensions(300, 100) --设置水平对其方式 gameRule:setHorizontalAlignment(cc.TEXT_ALIGNMENT_LEFT) --设置垂直对其方式 gameRule:setVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_TOP) ]] -- 创建把自己移除 动作解决方案 --[[ cc.RemoveSelf:create() ]] -- 场景切换解决方案 --[[ --StartScene 为脚本 --脚本内容为 --local StartScene = class("StartScene",cc.load("mvc").ViewBase) --function StartScene:onCreate() --必须的 --end -- 方案1 --local startScene = StartScene:create(self, "StartScene"):showWithScene("FADE", 1) --下面三种都可以 --cc.Director:getInstance():runWithScene(startScene) -- 需要调用场景的构造函数才能进入StartScene:create(self, "StartScene") --self:getApp():enterScene("StartScene") --cc.Director:getInstance():replaceScene(startScene) -- 方案2 self:runAction(cc.Sequence:create( cc.DelayTime:create(2), cc.CallFunc:create( function() --"FADE" 待扩展 --StartScene:create(self, "StartScene"):showWithScene("FADE", 1) end ) )); -- 方案3 self:runAction(cc.Sequence:create( cc.DelayTime:create(2), cc.CallFunc:create( function() --self:getApp():enterSceneEx("StartScene","FADE", 1) end ) )); -- 方案3 self:runAction(cc.Sequence:create( cc.DelayTime:create(2), cc.CallFunc:create( function() local myScene = cc.Scene:create() --cc.Director:getInstance():replaceScene(cc.TransitionSplitRows:create(2, myScene)) end ) )); --local EndScene = class("EndScene",function() --return cc.Scene:create(); --end) --local Obj = require("cocos.Packaging_Kernel") --必须是ctor --function EndScene:ctor() --self:InitData(); --end -- 方案4 建议用这个 或者3的方式 --好看好用 self:runAction(cc.Sequence:create( cc.DelayTime:create(2), cc.CallFunc:create( function() --local myScene = EndScene:create() --cc.Director:getInstance():replaceScene(cc.TransitionSplitCols:create(2, myScene)) end ) )); 至于popScene() 和pushScene() 就不建议用了 因为在popScene()回来的时候是不会调用构造函数的 (当前的场景在push时就已经执行了) ]] -- scene -- 场景切换解决方案 --[[ self:registerScriptHandler(function(eventType) print("registerScriptHandler "..eventType) if eventType == "enterTransitionFinish" then -- 进入场景而且过渡动画结束时候触发。 self:onEnterTransitionFinish() elseif eventType == "exitTransitionStart" then -- 退出场景而且开始过渡动画时候触发。 self:onExitTransitionStart() end end) eventType = "enter" 1、init() 初始化层调用(在类初始化时,只会调用一次)。 2、onEnter() 进入层时候调用(init初始完后进入,可能调用多次,如addChild一次就会调用一次)。 eventType = "enterTransitionFinish" 3、onEnterTransitionDidFinish() 进入层而且过渡动画结束时候调用(onEnter结束后进入)。 如果写了self:registerScriptHandler(function(eventType)end) 则不会调用 因为已经存在了"exitTransitionStart" 4、onExit() 退出层时候调用。 eventType = "exitTransitionStart" 5、onExitTransitionDidStart() 退出层而且开始过渡动画时候调用(onExit结束后进入)。 eventType = "cleanup" 6、cleanup() 层对象被清除时候调用(整个layer销毁时进入)。 ]] --[[ function GameViewLayer:LoadPlistFrame(filePathName,Position,beginFrame,endFrame,XMLImageName) -- local cache = cc.SpriteFrameCache:getInstance(); -- cache:addSpriteFrames(FilePathName); -- local Test = cc.Sprite:create(); -- Test:setPosition(Position); -- local animation = cc.Animation:create(); -- for i = beginFrame, endFrame do -- local bing = cache:getSpriteFrame(string.format(XMLImageName, i)); -- animation:addSpriteFrame(bing); -- end -- -- 设置单位延迟 -- animation:setDelayPerUnit(0.1); -- animation:setRestoreOriginalFrame(true); -- local action = cc.Animate:create(animation); -- Test:runAction(cc.RepeatForever:create(action)); end ]] --[[ for i = 0,100 do gameListContent:setPosition(cc.p(i * gameListContent:getContentSize().width + gameListContent:getContentSize().width / 2, 50)) end ]] --[[ --用户表情 function GameViewLayer:userExpression(wChairId,wChairId2,itemIdx) local ani_list = {"boom","dog","feidao","hongbao","qiang","tomato","touji","zuichun"} print("userExpression ------->"..string.format("%s %s %s", wChairId, wChairId2, itemIdx)) local vId1 = self._scene:SwitchViewChairID(wChairId) local vId2 = self._scene:SwitchViewChairID(wChairId2) local posX1 = self.nodePlayer[vId1]:getPositionX() local posY1 = self.nodePlayer[vId1]:getPositionY() local posX2 = self.nodePlayer[vId2]:getPositionX() local posY2 = self.nodePlayer[vId2]:getPositionY() local name = ani_list[itemIdx] local ani = sp.SkeletonAnimation:create("ani/"..name.."/skeleton.json", "ani/"..name.."/skeleton.atlas",1) ani:setPosition(posX1, posY1) self:addChild(ani,101) ani:setAnimation(1,"daji", true) ani:setTimeScale(0) ani:runAction(cc.Sequence:create( cc.MoveTo:create(0.8, cc.p(posX2,posY2)), cc.CallFunc:create(function() ani:setTimeScale(1) end) )) ani:registerSpineEventHandler( function(event) if event.type == "complete" then ani:unregisterSpineEventHandler(sp.EventType.ANIMATION_COMPLETE) ani:stopAllActions() ani:unscheduleUpdate() performWithDelay(ani,function() ani:removeFromParent() end ,0.1) end end,sp.EventType.ANIMATION_COMPLETE) local aniArr = {nil,"Eagle",nil,"RedPackage","Explode",nil,nil,nil} local aniArrTime = {0,3,0,1.1,1.0,0,0,0} name = aniArr[itemIdx] if (name) then ani:setVisible(false) local filePathName = "ani/" .. name .. "/" .. name .. ".csb" local csbNode = cc.CSLoader:createNode(filePathName) csbNode:setPosition(posX1, posY1) local start_Action = cc.CSLoader:createTimeline(filePathName) start_Action:setTimeSpeed(1.0) csbNode:runAction( cc.Sequence:create( cc.MoveTo:create(0.8, cc.p(posX2, posY2)), cc.CallFunc:create( function() self:OnCallFunc(filePathName, csbNode, cc.p(posX2, posY2),aniArrTime[itemIdx]) end ) )) self:addChild(csbNode, 101) end end function GameViewLayer:OnCallFunc(filePathName,csbNode,position,time) local aniNode = cc.CSLoader:createNode(filePathName) aniNode:setPosition(position) local start_Action = cc.CSLoader:createTimeline(filePathName) start_Action:setTimeSpeed(1.0) aniNode:runAction(start_Action) aniNode:runAction(cc.Sequence:create(cc.DelayTime:create(time), cc.CallFunc:create(function() aniNode:removeFromParent() end) )) start_Action:gotoFrameAndPlay(0, false) self:addChild(aniNode, 102) csbNode:removeFromParent() end ]] -- 迭代遍历参考 -- ipairs 是从0 + 1 开始的 没有数字下标是不会遍历的 只要不是字符串作为键值 -- 如 --[[ local Snake = { ["UP"] = { }, ["DOWN"] = { }, ["LEFT"] = { }, ["RIGHT"] = { }, } 是不会进循环的 ]] --[[ local Snake = { [1] = { }, [2] = { }, [3] = { }, [4] = { }, } 会进循环的 ]] -- 但这种可以(嵌套) --[[ local iterationDistanceY_Space = { { Key = 6, Value = 480 }, { Key = 9, Value = 240 }, { Key = 12, Value = 170 } } for k, v in ipairs(iterationDistanceY_Space) do print("k " .. k) print(" " .. iterationDistanceY_Space[k].Key .. " " .. iterationDistanceY_Space[k].Value) print("== " .. iterationDistanceY_Space[k].Value) print(" " .. v.Key .. " " .. v.Value) end local iterationDistanceY_Space = { { Key = "6", Value = 480 }, { Key = "9", Value = 240 }, { Key = "12", Value = 170 } } for k, v in pairs(iterationDistanceY_Space) do print("k " .. k) print(" " .. iterationDistanceY_Space[k].Key .. " " .. iterationDistanceY_Space[k].Value) print("== " .. iterationDistanceY_Space[k].Value) print(" " .. v.Key .. " " .. v.Value) end ]] --[[ local tabFiles = { [3] = "test2", [6] = "test3", [4] = "test1" } for k, v in pairs(tabFiles) do print(k, v) print(tabFiles[k]) end local tabFiles2 = { [1] = "test2", [6] = "test3", [2] = "test1" } for k, v in ipairs(tabFiles2) do print(tabFiles2[k]) end print("========================================") local iterationDistanceY_Space = { { Key = 6, Value = 480 }, { Key = 9, Value = 240 }, { Key = 12, Value = 170 } } for k, v in ipairs(iterationDistanceY_Space) do print("k " .. k) print(" " .. iterationDistanceY_Space[k].Key .. " " .. iterationDistanceY_Space[k].Value) print("== " .. iterationDistanceY_Space[k].Value) print(" " .. v.Key .. " " .. v.Value) end ]] -- 无限选择解决方案 --[[ Node:runAction(cc.RepeatForever:create(cc.RotateBy:create(1,30))) ]] -- 粒子 --[[ -- 每个粒子的生命 self.m_ParticleEffects:setLife(0.01) -- self.m_ParticleEffects:setLifeVar(1) ]] -- lua 数学函数解决方案 --[[ 函数名 描述 示例 结果 pi 圆周率 math.pi 3.1415926535898 abs 取绝对值 math.abs(-2012) 2012 ceil 向上取整 math.ceil(9.1) 10 floor 向下取整 math.floor(9.9) 9 max 取参数最大值 math.max(2,4,6,8) 8 min 取参数最小值 math.min(2,4,6,8) 2 pow 计算x的y次幂 math.pow(2,16) 65536 sqrt 开平方 math.sqrt(65536) 256 mod 取模 math.mod(65535,2) 1 modf 取整数和小数部分 math.modf(20.12) 20 0.12 randomseed 设随机数种子 math.randomseed(os.time()) random 取随机数 math.random(5,90) 5~90 rad 角度转弧度 math.rad(180) 3.1415926535898 deg 弧度转角度 math.deg(math.pi) 180 exp e的x次方 math.exp(4) 54.598150033144 log 计算x的自然对数 math.log(54.598150033144) 4 log10 计算10为底,x的对数 math.log10(1000) 3 frexp 将参数拆成x * (2 ^ y)的形式 math.frexp(160) 0.625 8 ldexp 计算x * (2 ^ y) math.ldexp(0.625,8) 160 sin 正弦 math.sin(math.rad(30)) 0.5 cos 余弦 math.cos(math.rad(60)) 0.5 tan 正切 math.tan(math.rad(45)) 1 asin 反正弦 math.deg(math.asin(0.5)) 30 acos 反余弦 math.deg(math.acos(0.5)) 60 atan 反正切 math.deg(math.atan(1)) 45 函数名 描述 示例 结果 pi 圆周率 math.pi 3.1415926535898 abs 取绝对值 math.abs(-2012) 2012 ceil 向上取整 math.ceil(9.1) 10 floor 向下取整 math.floor(9.9) 9 max 取参数最大值 math.max(2,4,6,8) 8 min 取参数最小值 math.min(2,4,6,8) 2 pow 计算x的y次幂 math.pow(2,16) 65536 sqrt 开平方 math.sqrt(65536) 256 mod 取模 math.mod(65535,2) 1 modf 取整数和小数部分 math.modf(20.12) 20 0.12 randomseed 设随机数种子 math.randomseed(os.time()) random 取随机数 math.random(5,90) 5~90 rad 角度转弧度 math.rad(180) 3.1415926535898 deg 弧度转角度 math.deg(math.pi) 180 exp e的x次方 math.exp(4) 54.598150033144 log 计算x的自然对数 math.log(54.598150033144) 4 log10 计算10为底,x的对数 math.log10(1000) 3 frexp 将参数拆成x * (2 ^ y)的形式 math.frexp(160) 0.625 8 ldexp 计算x * (2 ^ y) math.ldexp(0.625,8) 160 sin 正弦 math.sin(math.rad(30)) 0.5 cos 余弦 math.cos(math.rad(60)) 0.5 tan 正切 math.tan(math.rad(45)) 1 asin 反正弦 math.deg(math.asin(0.5)) 30 acos 反余弦 math.deg(math.acos(0.5)) 60 atan 反正切 math.deg(math.atan(1)) 45 ]] --lua 引用解决方案 --[[ self._recordList = clone(pData) ]] -- 不意味着跨平台 -- 返回程序所用CPU时间(以秒为单位)的近似值。 --[[ os.clock():获取lua代码运行时间 解释:返回一个程序使用CPU时间的一个近似值。 -- 记录开始时间 local starttime = os.clock(); --> os.clock()用法 print(string.format("start time : %.4f", starttime)); -- 进行耗时操作 local sum = 0; for i = 1, 100000000 do sum = sum + i; end -- 记录结束时间 local endtime = os.clock(); --> os.clock()用法 print(string.format("end time : %.4f", endtime)); print(string.format("cost time : %.4f", endtime - starttime)); 结果: 总结: 从使用上来看这个函数很简单,程序开始的时候调用一次,结束的时候调用一次,然后做差值就可以了。 我们结果上来看一下,为什么start time不是0呢,原因就是我第一次调用clock()的地方并不是程序的开始,之前还做了一些其他的操作,导致了这里有0.027s的误差。 需要注意的是这个lua函数的实现是调用了c语言的函数函数库,实现代码如下: static int os_clock (lua_State *L) { lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC); return 1; } 其中有个CLOCKS_PER_SEC值,在不同平台有着不同的定义,所以一定要注意函数的溢出问题,程序运行时间太长的话,使用clock有可能就会返回负数。 还有很多讨论是关于clock在不同平台的表现不同,在多线程会有影响等问题的,其实我也做了一些测试,有些结果和讨论中的一致, 有些是相反的,这也许与平台相关吧,比如我举一个例子, 在两个clock调用之间加入Sleep(1000),那么Sleep的时间是算入clock的(Windows平台+VS2008), 但是很多帖子是说测试结果表明,Sleep这段时间不算入clock。 ]] -- clock 一些解决方案 --[[ os.clock() 返回程序使用的按秒计CPU时间的近似值。 那么就可以很愉快的搞定这个需求了: local test = {} function test:clickBtn() local curTime = os.clock() if test.recordTime and curTime - test.recordTime < 2 then print("2s cd中") return end -- do something test.recordTime = curTime end 本来以为这样就OK了,万万没想到,os.clock()居然偶尔会返回一个负数!所以就直接GG了!!! 网上搜了一下发现有不少人也都遇到过这个问题,返回负数的原因是Lua的os.clock()会调用C的clock函数,该函数返回值依赖于操作系统,在32为系统中会有溢出风险! 那么怎么解决这个问题呢?很简单,用socket.gettime()或者os.time()来替换os.clock()获取时间即可! local test = {} local socket = require("socket") function test:clickBtn() local curTime = socket.gettime() print(curTime) if test.recordTime and curTime - test.recordTime < 2 then print("2s cd中") return end -- do something test.recordTime = curTime end 对时间精度要求高就用socket.gettime(),对时间精度要求不高就用os.time()! --------------------- 作者:fightsyj 来源:CSDN 原文:https://blog.csdn.net/fightsyj/article/details/86258240 版权声明:本文为博主原创文章,转载请附上博文链接! ]] -- 动作解决方案 --[[ //// Action动作 // // CCMoveBy 创建一个移动的动作 参数1:移动到目标坐标所需的时间 参数2:目标坐标 支持reverse 可以获取其反向动作 // CCMoveTo 一样的 // CCActionInterval * moveBy = CCMoveBy::create(5,ccp(300, 100)); // CCActionInterval * actionmoveback= moveBy->reverse(); // sp->runAction(actionmoveback); // // CCScaleTo 作用:创建一个缩放的动作 // 参数1:达到缩放大小所需的时间 // 参数2 :缩放的比例 // CCActionInterval * scaleto = CCScaleTo ::create(2, 2); // sp->runAction(scaleto); // // CCScaleBy 作用:创建一个缩放的动作 // 参数1:达到缩放大小的所需时间 参数2:缩放比例 // CCActionInterval * scaleby = CCScaleBy::create(2, 2); // CCActionInterval * actionbyback = scaleby->reverse(); // sp->runAction(actionbyback); // // CCRotateTo // 作用创建一个旋转的动作 // 参数1:旋转的时间 参数2:旋转饿角度 0 - 360 // CCActionInterval * rotateto = CCRotateTo::create(2, 90); // sp->runAction(rotateto); // // CCSkewTo // 作用创建一个倾斜的动作 // 参数1:倾斜到特定角度所需的时间 // 参数2:x轴的倾斜角度 // 参数3:y轴的倾斜角度 // CCActionInterval * skewto = CCSkewTo::create(2, 10, 10); // sp->runAction(skewto); // // CCJumpTo // 作用:创建一个跳的动作 // 参数1:跳到目标动作位子的所需时间 // 参数2:目标位置 // 参数3:跳的高度 // 参数4跳到目标位置的次数 // CCActionInterval* jumpto = CCJumpTo ::create(2, ccp(300, 200), 50, 4 ); // sp->runAction(jumpto); // // CCJumpBy // 作用:创建一个跳的动作 // 参数1:跳到目标动作位子的所需时间 // 参数2:目标位置 // 参数3:跳的高度 // 参数4跳到目标位置的次数 // 这个支持方向动作reverse // CCActionInterval * jumpby = CCJumpBy ::create(3, ccp(300, 200), 50, 4); // CCActionInterval * ac= jumpby->reverse(); // sp->runAction(ac); // CCBezier // ccBezierConfig结构体 // ccBezierConfig bezierCon; // bezierCon.controlPoint_1=CCPointMake(200, 150);//控制点1 // bezierCon.controlPoint_2=CCPointMake(200, 160);//控制点2 // bezierCon.endPosition =CCPointMake(340, 100);// 结束位置 // CCBezierTo // 创建一个贝塞尔曲线运动的动作 // 参数1:贝塞尔曲线运动的时间 // 参数2 :ccBezierConfig结构体 // CCActionInterval * action = CCBezierTo::create(2, bezierCon); // CCActionInterval * action = CCBezierBy::create(3, bezierCon);//支持反向 // CCActionInterval * action1 = action->reverse(); // sp->runAction(action1); // CCFadeIn // 作用:创建一个渐变出现的动作 // 参数是时间 // CCActionInterval * fadein = CCFadeIn::create(2); // sp->runAction(fadein); // CCFadeOut // 作用:创建一个渐变消失的动作 // 参数是时间 // CCActionInterval * fadeout = CCFadeOut::create(2); // sp->runAction(fadeout); // CCTintTo // 作用:创建一个色彩变化的消失动作 // 参数1:色彩变化的动作 // 参数2 :红色分量 // 参数3:蓝色分量 // CCActionInterval * tinto = CCTintTo ::create(3, 255, 255, 0); // sp->runAction(tinto); // CCTintBy // 作用:创建一个色彩变化的出现动作 // 参数1:色彩变化的动作 // 参数2 :红色分量 // 参数3:蓝色分量 但是家了reverse就是 反向的 // CCActionInterval * tintby = CCTintBy::create(3, 0, 255, 255); // CCActionInterval * tintby1 = tintby->reverse(); // sp->runAction(tintby1); // CCBlink // 作用 :创建一额闪烁的动作 // 参数1:闪烁完成的时间 // 参数2:闪烁的次数 // CCActionInterval * blink = CCBlink ::create(3, 10); // sp->runAction(blink); // CCDelayTime // 创建一个延迟的动作 // 参数 延迟的时间 // CCActionInterval * delaytime = CCDelayTime::create(3); // sp->runAction(delaytime); // CCOrbitCamera // 作用:创建一个球面坐标轨迹进行旋转的动作 // 参数1 : 旋转轨迹的时间 // 参数2 :起始半径 // 参数3:半径差 // 参数4:起始z角 // 参数5:旋转z角的差 // 参数6:起始x角 // 参数7:旋转x角的差 // CCActionInterval * orbitcamera = CCOrbitCamera::create(3, 10, 0, 45, 180, 90, 0); // sp->runAction(orbitcamera); // CCCardinalSpline // 作用:创建数组 点的数组 CCPointArray * array = CCPointArray::create(20); array->addControlPoint(ccp(0,0)); array->addControlPoint(ccp(210,0)); array->addControlPoint(ccp(210,240)); array->addControlPoint(ccp(0,160)); array->addControlPoint(ccp(0,0)); // CCCardinalSplineTo // 作用:创建一个样条曲线轨迹的动作 // 参数1:完成轨迹所需的时间 // 参数2:控制点的坐标数组 // 拟合度 其值= 0 路径最柔和 // CCActionInterval * CardinalSplineTo=CCCardinalSplineTo::create(3, array, 0); // sp->runAction(CardinalSplineTo); // CCCardinalSplineBy // 作用:创建一个样条曲线轨迹的动作 // 参数1:完成轨迹所需的时间 // 参数2:控制点的坐标数组 // 拟合度 其值= 0 路径最柔和 // CCActionInterval * CardinalSplineBy = CCCardinalSplineBy::create(3, array, 0); // sp->runAction(CardinalSplineBy); // CCCatmullRomTo CCCatmullRomBY // 作用:创建一个样条插值轨迹 // 参数1:完成轨迹的时间 // 参数2:控制点的数组坐标 // CCActionInterval * catmullRomTo = CCCatmullRomTo::create(3, array); // sp->runAction(catmullRomTo); // CCFollow // 作用:创建一个跟随动作 // 参数1:跟随的目标对象 // 跟随范围,离开范围就不再跟随 //创建一个参照物spT // CCSprite * spt = CCSprite::create("Icon.png"); // spt->setPosition(ccp(420,40)); // addChild(spt); // sp->runAction(CCMoveTo::create(3, ccp(940,sp->getPositionY()))); // // CCFollow * follow = CCFollow::create(sp,CCRectMake(0, 0, 960, 320)); // this-> runAction(follow); // CCEaseBounceIn // 目标动作 // CCActionInterval* move = CCMoveTo::create(3, ccp(300, sp->getPositionY())); // 让目标动作缓慢开始 // 参数:目标动作 // CCActionInterval * EaseBounceIn = CCEaseBounceIn::create(move); // sp->runAction(EaseBounceIn); // CCEaseBounceOut // 作用:让目标动作赋予反弹力,且以目标动作结束位子开始反弹 // 参数目标动作 // CCActionInterval * easeBounceOut = CCEaseBounceOut ::create(move); // sp->runAction(easeBounceOut); // CCEaseBounceInOut // 作用:让目标动作赋予反弹力,且以目标动作起始与结束位子开始反弹 // CCActionInterval * easeBounceInOut= CCEaseBounceInOut::create(move); // sp->runAction(easeBounceInOut); // CCEaseBackIn // 作用:让目标动作赋予回力 , 且以目标动作起点位置作为回力点 // 参数:目标动作 // CCActionInterval * easeBackIn = CCEaseBackIn::create(move); // sp->runAction(easeBackIn); // CCEaseBackOut // 作用:让目标动作赋予回力 , 且以目标动作终点位置作为回力点 // 参数:目标动作 // CCActionInterval *easeBackOut = CCEaseBackOut::create(move); // sp->runAction(easeBackOut); // CCEaseBackInOut // 作用:让目标动作赋予回力 , 且以目标动作起点和终点位置作为回力点 // 参数:目标动作 // CCActionInterval * easeBackInOut = CCEaseBackInOut::create(move); // sp->runAction(easeBackInOut); // CCEaseElasticIn // 作用:让目标动作赋予弹性 ,且以目标动作起点位子赋予弹性 // 参数:目标动作 // CCActionInterval * easeElasticIn= CCEaseElasticIn::create(move); // sp->runAction(easeElasticIn); // CCEaseElasticOut // 作用:让目标动作赋予弹性 ,且以目标动作终点位子赋予弹性 // 参数:目标动作 // CCActionInterval *easeElasticOut = CCEaseElasticOut::create(move); // sp->runAction(easeElasticOut); // CCEaseElasticInOut // 作用:让目标动作赋予弹性 ,且以目标动作起点和终点位子赋予弹性 // 参数:目标动作 // CCActionInterval *easeElasticInOut = CCEaseElasticOut::create(move); // sp->runAction(easeElasticInOut); // CCEaseExponentialIn // 让目标动作缓慢开始 // 参数:目标动作 // CCActionInterval * easeExponentialIn= CCEaseExponentialIn::create(move); // sp->runAction(easeExponentialIn); // CCEaseExponentialOut // 让目标动作缓慢中止 // 参数:目标动作 // CCActionInterval * easeExponentialIn= CCEaseExponentialOut::create(move); // sp->runAction(easeExponentialIn); // CCEaseExponentialInOut // 让目标动作缓慢开始和中止 // 参数:目标动作 // CCActionInterval * easeExponentialInOut= CCEaseExponentialInOut::create(move); // sp->runAction(easeExponentialInOut); // CCEaseRateAction // 作用 : 让目标动作设置速率 // 参数1:目标动作 // 参数2:速率 // CCActionInterval * move = CCMoveTo::create(5, ccp(300,sp->getPositionY())); // CCActionInterval * easeRateAction = CCEaseRateAction::create(move, 3); // sp->runAction(easeRateAction); // CCEaseSineIn // 作用:动作由慢到快 // 参数:目标动作 // CCActionInterval * easeSineIn = CCEaseSineIn::create(move); // sp->runAction(easeSineIn); // CCEaseSineOut // 作用:动作由快到慢 // 参数:目标动作 // CCActionInterval * easeSineOut = CCEaseSineOut::create(move); // sp->runAction(easeSineOut); // CCEaseSineInOut // 作用:动作由慢到快再快到慢 // 参数:目标动作 // CCActionInterval * easeSineInOut = CCEaseSineInOut::create(move); // sp->runAction(easeSineInOut); // CCSpeed // 作用:让目标动作运行速度加倍 // 参数1:目标动作 // 参数2:倍速 // CCActionInterval * move = CCMoveTo::create(10, ccp(300,sp->getPositionY())); // CCSpeed * speed =CCSpeed::create(move, 100); // sp->runAction(speed); // CCSpawn // 作用:让多个动作同时执行 // 参数:目标动作的可变参数 // CCActionInterval * move = CCMoveTo::create(10, ccp(300,sp->getPositionY())); // CCActionInterval * scale = CCScaleTo::create(2, 3); // CCActionInterval * rotate = CCRotateTo::create(4, 190); // CCFiniteTimeAction * spawn =CCSpawn::create(move,scale,rotate,NULL); // sp->runAction(spawn); // CCSequence // 作用:让多个动作按照前后顺序逐一执行 // 参数:目标动作的可变参数 // CCActionInterval * move = CCMoveTo::create(2, ccp(300, sp->getPositionY())); // CCActionInterval * scale = CCScaleTo::create(2, 3); // CCFiniteTimeAction * seq= CCSequence::create(move,scale,NULL); // sp->runAction(seq); // 扩展如果要对目标动作全部进行方向运动,可以使用如下形式操作 // CCFiniteTimeAction *seq=CCSequence::create(moveby,scaleby,...NULL); // CCFiniteTimeAction * reverseseq = CCSequence::create(seq,seq->reverse(),NULL) // 注意CCSequence中的所有动作都必须支持reverse函数,否则会出现异常 // CCActionInterval * move = CCMoveBy::create(2, ccp(300, sp->getPositionY())); // CCActionInterval * scale = CCScaleBy::create(2, 3); // CCFiniteTimeAction * seq= CCSequence::create(move,scale,NULL); // CCFiniteTimeAction * reveseseq = CCSequence::create(seq,seq->reverse(),NULL); // sp->runAction(reveseseq); // CCRepeat // 作用:对目标动作进行重复运动(目标动作可以是CCSequence ,CCSpawn) // 参数1:目标动作 // 参数2:重复次数 // CCActionInterval * move = CCMoveTo::create(2, ccp(300, sp->getPositionY())); // CCActionInterval * move2 = CCMoveTo::create(2, ccp(100,100)); // CCFiniteTimeAction*seq =CCSequence::create(move,move2,NULL); // CCFiniteTimeAction *repeat = CCRepeat::create(seq, 3); // sp->runAction(repeat); // CCRepeatForever // 作用:对目标动作进行永久性的重复运动(目标动作可以是CCSequence ,CCSpawn) // 参数:目标动作 // CCActionInterval * move = CCMoveTo::create(1, ccp(300, sp->getPositionY())); // CCActionInterval * move1 = CCMoveTo::create(1, ccp(100,100)); // CCFiniteTimeAction* seq = CCSequence::create(move,move1,NULL); // CCActionInterval * repeatForever =CCRepeatForever::create((CCActionInterval* )seq); // sp->runAction(repeatForever); // CCCallFunc // 作用:创建一个回调动作(调用不带参数的回调方法); // 参数1:目标动作 // 参数2:目标回调函数 // CCActionInterval * move = CCMoveTo::create(1, ccp(300, sp->getPositionY())); // CCCallFunc * funcall= CCCallFunc::create(this, callfunc_selector(HelloWorld::callbackC)); // CCFiniteTimeAction * seq = CCSequence::create(move,funcall,NULL); // sp->runAction(seq); // CCCallFuncN // 作用:创建一个回调动作(调用 带一个参数的回调方法); // 参数1:目标动作 // 参数2:目标回调函数 // CCActionInterval * move = CCMoveTo::create(1, ccp(300, sp->getPositionY())); // CCCallFuncN * funcall= CCCallFuncN::create(this, callfuncN_selector(HelloWorld::callbackN)); // CCFiniteTimeAction * seq = CCSequence::create(move,funcall,NULL); // sp->runAction(seq); // CCCallFuncND // 作用:创建一个回调动作(调用 带两个参数的回调方法); // 参数1:目标动作 // 参数2:目标回调函数 CCActionInterval * move = CCMoveTo::create(1, ccp(300, sp->getPositionY())); CCCallFuncND * funcall= CCCallFuncND::create(this, callfuncND_selector(HelloWorld::callbackND) ,(void*)0xbebabeba); CCFiniteTimeAction * seq = CCSequence::create(move,funcall,NULL); sp->runAction(seq); return true; } void HelloWorld::callbackC() { CCLOG("callbackC"); } void HelloWorld::callbackN(CCNode* sender) { CCLOG("callbackN"); } void HelloWorld::callbackND(CCNode* sender, void* data) { CCLOG("callbackND"); } ]] -- 平台判定解决方案 --[[ device.platform == "windows" or device.platform == "android" ]] -- 获取当前运行场景解决方案 --[[ --local scene = cc.Director:getInstance():getRunningScene() self:runAction(cc.Sequence:create(cc.DelayTime:create(5),cc.CallFunc:create(function() local scene = cc.Director:getInstance():getRunningScene() if(scene)then local S = cc.Sprite:create("ParticleSystem/guangdian.png") S:setScale(5.0) S:setPosition(display.center) scene:addChild(S) end end))) ]] -- 获取当前程序运行路径解决方案 --[[ print("cc.FileUtils:getInstance():getWritablePath() "..cc.FileUtils:getInstance():getWritablePath()) ]] -- 观察者解决方案 -- EventListenerCustom 解决方案1 -- eventDispatcher:removeEventListener(listener) --[[ local eventDispatcher = cc.Director:getInstance():getEventDispatcher() local scene = cc.Director:getInstance():getRunningScene() if (scene) then local S = cc.Sprite:create("ParticleSystem/guangdian.png") S:setScale(5.0) S:setPosition(display.center) scene:addChild(S) end self.BetTimeEndSystemListener = cc.EventListenerCustom:create("BetTimeEndSystem", function() local tmpAction = cc.Spawn:create(cc.MoveTo:create(0.15, cc.p(1145, 644)), cc.ScaleTo:create(0.15, 0.3, 0.3, 0.3)) S:runAction(cc.Sequence:create(tmpAction, cc.CallFunc:create( function() self:removeFromParent(true) end ))) if self.BetTimeEndSystemListener then eventDispatcher:removeEventListener(self.BetTimeEndSystemListener) end end ) eventDispatcher:addEventListenerWithFixedPriority(self.BetTimeEndSystemListener, 1) ]] -- 观察者解决方案 -- EventListenerCustom 解决方案2 -- eventDispatcher:removeEventListener(listener) --[[ local function serverTimeChangedCallback(event) print("data:"..event.data) end local listener = cc.EventListenerCustom:create("serverTimeChanged",serverTimeChangedCallback) local eventDispatcher = self:getEventDispatcher() eventDispatcher:addEventListenerWithFixedPriority(listener, 1) local event = cc.EventCustom:new("serverTimeChanged") event.data = "serverTimeChanged!" eventDispatcher:dispatchEvent(event) event = cc.EventCustom:new("serverTimeChanged") event.data = "server!" eventDispatcher:dispatchEvent(event) ]] -- 观察者解决方案 -- EventListenerCustom 解决方案3 -- eventDispatcher:removeEventListener(listener) --[[ local function EventListenerCustomCallBack(event) print("data: "..event.data) end local eventDispatcher = cc.Director:getInstance():getEventDispatcher() local listener = cc.EventListenerCustom:create("EventListenerCustom",EventListenerCustomCallBack) eventDispatcher:addEventListenerWithFixedPriority(listener,1) --要和EventListenerCustom 名字一样 local event = cc.EventCustom:new("EventListenerCustom") event.data = "Hello World" eventDispatcher:dispatchEvent(event) event = cc.EventCustom:new("EventListenerCustom") event.data = "Hello World!" eventDispatcher:dispatchEvent(event) ]] -- 观察者解决方案 -- EventListenerCustom 解决方案4 -- eventDispatcher:removeEventListener(listener) --[[ local function serverTimeChangedCallback(event) print("serverTimeChanged serverTimeChanged ") print("event "..event.data) end local listener = cc.EventListenerCustom:create("serverTimeChanged", serverTimeChangedCallback) local eventDispatcher = cc.Director:getInstance():getEventDispatcher() eventDispatcher:addEventListenerWithFixedPriority(listener, 1) local event = cc.EventCustom:new("serverTimeChanged") event.data = "Hello World" eventDispatcher:dispatchEvent(event) ----------------------- --作者:themagickeyjianan --来源:CSDN --原文:https://blog.csdn.net/themagickeyjianan/article/details/51841652 --版权声明:本文为博主原创文章,转载请附上博文链接! ]] -- ANY 解决方案 --[[ -- -- 游戏列表创建图标 -- local listView = ccui.ListView:create() -- -- 设置方向为h横向方向 -- listView:setDirection(2) -- -- 触摸反弹 -- listView:setBounceEnabled(true) -- listView:setTouchEnabled(true) -- -- 滑动惯性 -- listView:setContentSize(750, 80) -- listView:setPosition(cc.p(0, display.height - 110 - 80)) -- self._btnlayerOut = ccui.Layout:create() -- self._btnlayerOut:setContentSize(1176, 80) -- listView:pushBackCustomItem(self._btnlayerOut) -- -- self._listView:jumpToRight() -- listView:setScrollBarEnabled(false) -- self:addChild(listView) -- local btcallback = function(ref, type) -- if type == ccui.TouchEventType.ended then -- self:onButtonClickedEvent(ref:getTag(), ref) -- end -- end -- local edlistener = function(sender, eventType) -- self:onEditEvent(sender, eventType) -- end -- local btnPos = { } -- local startY = display.height - 110 - 40 -- local distanceY = 80 -- btnPos = { 84, 252, 404, 572, 740, 908, 1072 } -- -- 游戏列表创建图标 -- -- local btnPos = {} -- -- local startY = display.height - 110 - 40 -- -- local distanceY = 80 -- -- btnPos[1] = {display.width * 0.5} -- -- btnPos[2] = {display.width * 0.5 - 84,display.width * 0.5 + 84} -- -- btnPos[3] = {display.width * 0.5 - 168,display.width * 0.5,display.width * 0.5 + 168} -- -- btnPos[4] = {display.width * 0.5 - 252,display.width * 0.5 - 84,display.width * 0.5 + 84,display.width * 0.5 + 252} -- local rows = math.ceil(#self._gameList / 7) -- local lastCount = #self._gameList -(rows - 1) * 7 -- for i = 1, #self._gameList do -- local curRow = math.ceil(i / 7) -- local btnPath_1 = string.format("Privatemode/btn_game_%d_1.png", tonumber(self._gameList[i]._KindID)) -- local btnPath_2 = string.format("Privatemode/btn_game_%d_2.png", tonumber(self._gameList[i]._KindID)) -- local checkbox = ccui.CheckBox:create(btnPath_1, "", btnPath_2, "", "") -- checkbox:setPosition(btnPos[i], 40) -- checkbox:setTag(BTN_GAME_START + i) -- checkbox:addEventListener(cbtlistener) -- self._btnlayerOut:addChild(checkbox) -- -- 最后一排坐标修正 -- -- if curRow == rows and lastCount ~= 0 then -- -- checkbox:setPosition(btnPos[lastCount][(i - 1) % 4 + 1],startY - (curRow - 1) * distanceY) -- -- end -- if i == self._select then -- checkbox:setSelected(true) -- else -- checkbox:setSelected(false) -- end -- end cc.LabelAtlas:create(i,"Number/num_join_room.png",28,38,string.byte("0")) :setAnchorPoint(0.5,0.5) :setPosition(btn:getContentSize().width * 0.5 ,btn:getContentSize().height * 0.5) :addTo(btn) ]] -- 9宫格解决方案 --[[ local bg = ccui.Scale9Sprite:create("bg_common_1.png") bg:setScale9Enabled(true) bg:setPosition(display.center) bg:setContentSize(bg:getContentSize().width, 1024) self:addChild(bg) ]] -- 窗口解决方案 --[[ -- 背景图 local bg = ccui.Scale9Sprite:create("bg_common_1.png") bg:setScale9Enabled(true) bg:setPosition(display.center) bg:setContentSize(bg:getContentSize().width, 1024) self:addChild(bg) --标题 display.newSprite("Title/title_join_club.png") :setPosition(bg:getPositionX(),display.height * 0.5 + bg:getContentSize().height * 0.5 - 42) :addTo(self) --关闭按钮 local btn = ccui.Button:create("Button/btn_close.png","Button/btn_close.png") btn:setPosition(bg:getPositionX() + bg:getContentSize().width * 0.5 - 40,display.height * 0.5 + bg:getContentSize().height * 0.5 - 40) btn:setTag(BTN_CLOSE) btn:addTouchEventListener(btcallback) self:addChild(btn) ]] -- 单选框解决方案 --[[ --1 2 local presenter = ccui.CheckBox:create("Privatemode/check_box_1.png", "Privatemode/check_box_2.png") presenter:setPosition(cc.p(appdf.WIDTH * 0.5 + position_x[i], appdf.HEIGHT * 0.5 + position_y[i])) presenter:setTag(TAG_INTEGRAL_START + i) presenter:addEventListener(cbtlistener) self.layer:addChild(presenter) ]] -- 颜色层创建解决方案 --[[ local layer = cc.LayerColor:create(cc.c4b(100, 100, 100, 100)) layer:setAnchorPoint(0, 0) layer:setContentSize(viewWidth, viewHeight) layer:setPosition(viewposX, viewposY) layer:setVisible(false) self:addChild(layer) ]] -- 按钮解决方案 --[[ --关闭按钮 local btn = ccui.Button:create("Button/btn_close.png","Button/btn_close.png") btn:setPosition(bg:getPositionX() + bg:getContentSize().width * 0.5 - 40,display.height * 0.5 + bg:getContentSize().height * 0.5 - 40) btn:addClickEventListener(function(sender) layer:removeChild(sender) end) layer:addChild(btn) ]] --测试解决方案 --[[ display.newLayer(cc.c4b(100,100,100)) :setContentSize(viewWidth, viewHeight) :addTo(bg) :setPosition(0,cellHeight + 20) ]] -- tableView 测试解决方案 -----//////////////////////////////////////////////////////////////////// lua Project --[[ local RetroSnaker = class("RetroSnaker", function() return cc.Layer:create(); end ) local Obj = require("cocos.Packaging_Kernel") local KEY_UP = 28 local KEY_DOWN = 29 local KEY_LEFT = 26 local KEY_RIGHT = 27 local Snake = { ["UP"] = { }, ["DOWN"] = { }, ["LEFT"] = { }, ["RIGHT"] = { } } local SnakePoint = { } local struct = { } struct.SnakePosition = { } function struct.COOR() local Coor = { } Coor = cc.p(0, 0); return Coor end function struct.SnakeDirName() local SnakeDir = { UP = "UP", DOWN = "DOWN", LEFT = "LEFT", RIGHT = "RIGHT" } return SnakeDir; end function struct.SnakeDirCode() local SnakeDirCode = { UP = 28, DOWN = 29, LEFT = 26, RIGHT = 27 } return SnakeDirCode; end function struct.FOOD() local Food = { } Food.COOR = struct.COOR() Food.Flag = 0; return Food; end function struct.SNAKE() struct.Len = 30; struct.MaxLen = 100; struct.Dir = struct.SnakeDirCode().RIGHT for i = 0, struct.MaxLen - 1 do struct.SnakePosition[i + 1] = { } struct.SnakePosition[i + 1] = struct.COOR() end return struct; end function struct.SetSnakePosition(Position) struct.SnakePosition[0] = Position; end local Switch = { } Switch.Value = { } function Switch.switch(Value) Switch.Value = Value; end function Switch.case(Value, Function) if (Switch.Value == Value) then Function() end end local if_s = { } if_s.bool = { } function if_s.ifs(bool) if_s.bool = bool return bool end function if_s.elseifs(bool) if_s.bool = bool return bool end function if_s.Call(Function) if (if_s.bool == true) then Function() end end function if_s.elses(Function) if (if_s.bool == false) then Function() end end function RetroSnaker:ctor() -- AudioEngine.playMusic(cc.FileUtils:getInstance():fullPathForFilename("RetroSnaker/BackgroundMusic.mp3"), true); self:InitData() end function RetroSnaker:InitData() self:CreateKeyEvent() -- self:CreateFrameCall() self:CreateTimeFrameCall(0.2) Snake["UP"] = cc.Sprite:create("RetroSnaker/SnakeUp.png") Snake["UP"]:setPosition(display.center) self:addChild(Snake["UP"]) Snake["DOWN"] = cc.Sprite:create("RetroSnaker/SnakeDown.png") Snake["DOWN"]:setPosition(display.center) self:addChild(Snake["DOWN"]) Snake["LEFT"] = cc.Sprite:create("RetroSnaker/SnakeLeft.png") Snake["LEFT"]:setPosition(display.center) self:addChild(Snake["LEFT"]) Snake["RIGHT"] = cc.Sprite:create("RetroSnaker/SnakeRight.png") Snake["RIGHT"]:setPosition(display.center) self:addChild(Snake["RIGHT"]) for Key, Value in pairs(Snake) do print("call") print(Key) Value:setVisible(false) end Snake["RIGHT"]:setVisible(true) self.CurSnakeHead = Snake["RIGHT"] self.CurSnakeHead:setTag(struct.SnakeDirCode().RIGHT) struct.SNAKE(); for i = 0, struct.Len - 1 do struct.SnakePosition[i + 1] = cc.p(display.cx - i * 50,display.cy) end end function RetroSnaker:SnakeRefresh() local i = struct.Len; while(i > 1)do struct.SnakePosition[i].x = struct.SnakePosition[i - 1].x; struct.SnakePosition[i].y = struct.SnakePosition[i - 1].y; i = i - 1 end end function RetroSnaker:SnakeBody() local i = struct.Len; while(i > 1)do if(self:getChildByName("SnakeBody"..i) == nil)then local SnakeBody = cc.Sprite:create("RetroSnaker/SnakeBody.png") --防止与蛇头的Tag的冲突 SnakeBody:setName("SnakeBody"..i) SnakeBody:setPosition(struct.SnakePosition[i].x,struct.SnakePosition[i].y) self:addChild(SnakeBody) else self:getChildByName("SnakeBody"..i):setPosition(struct.SnakePosition[i].x,struct.SnakePosition[i].y) end i = i - 1 end end function RetroSnaker:SnakeMove() print("SnakeMove") self:SnakeRefresh() --上面这个函数虽然设置了坐标,但蛇头的坐标未改变 Switch.switch(struct.Dir) Switch.case(struct.SnakeDirCode().UP, function() struct.SnakePosition[1].y = struct.SnakePosition[1].y + 50; if (self.CurSnakeHead:getTag() ~= struct.SnakeDirCode().UP) then self.CurSnakeHead:setVisible(false) self.CurSnakeHead = Snake["UP"] self.CurSnakeHead:setVisible(true) self.CurSnakeHead:setTag(struct.SnakeDirCode().UP) end self.CurSnakeHead:setPosition(struct.SnakePosition[1]) end ) Switch.case(struct.SnakeDirCode().DOWN, function() struct.SnakePosition[1].y = struct.SnakePosition[1].y - 50; if (self.CurSnakeHead:getTag() ~= struct.SnakeDirCode().DOWN) then self.CurSnakeHead:setVisible(false) self.CurSnakeHead = Snake["DOWN"] self.CurSnakeHead:setVisible(true) self.CurSnakeHead:setTag(struct.SnakeDirCode().DOWN) end self.CurSnakeHead:setPosition(struct.SnakePosition[1]) end ) Switch.case(struct.SnakeDirCode().LEFT, function() struct.SnakePosition[1].x = struct.SnakePosition[1].x - 50; if (self.CurSnakeHead:getTag() ~= struct.SnakeDirCode().LEFT) then self.CurSnakeHead:setVisible(false) self.CurSnakeHead = Snake["LEFT"] self.CurSnakeHead:setVisible(true) self.CurSnakeHead:setTag(struct.SnakeDirCode().LEFT) end self.CurSnakeHead:setPosition(struct.SnakePosition[1]) end ) Switch.case(struct.SnakeDirCode().RIGHT, function() struct.SnakePosition[1].x = struct.SnakePosition[1].x + 50; if (self.CurSnakeHead:getTag() ~= struct.SnakeDirCode().RIGHT) then self.CurSnakeHead:setVisible(false) self.CurSnakeHead = Snake["RIGHT"] self.CurSnakeHead:setVisible(true) self.CurSnakeHead:setTag(struct.SnakeDirCode().RIGHT) end self.CurSnakeHead:setPosition(struct.SnakePosition[1]) end ) --头先移动再试身体移动 self:SnakeBody() end function RetroSnaker:Updata(interval) print(interval) print("Update Call") end function RetroSnaker:UpdateTimer(Time) print(Time) print("UpdateTimer Call") print("Snake Dir " .. struct.Dir) self:SnakeMove() end -- 按下 function RetroSnaker:OnKeyPressed(KeyCode, Event) print(" OnKeyPressed " .. KeyCode) end -- 抬起 function RetroSnaker:OnKeyReleased(KeyCode, Event) print(" OnKeyReleased " .. KeyCode) Switch.switch(KeyCode) Switch.case(struct.SnakeDirCode().UP, function() print("UP") struct.Dir = struct.SnakeDirCode().UP; end ) Switch.case(struct.SnakeDirCode().DOWN, function() print("DOWN") struct.Dir = struct.SnakeDirCode().DOWN; end ) Switch.case(struct.SnakeDirCode().LEFT, function() print("LEFT") struct.Dir = struct.SnakeDirCode().LEFT; end ) Switch.case(struct.SnakeDirCode().RIGHT, function() print("RIGHT") struct.Dir = struct.SnakeDirCode().RIGHT; end ) end function RetroSnaker:CreateFrameCall() -- 每一帧调用 local function handler(interval) self:Updata(interval); end self:scheduleUpdateWithPriorityLua(handler, 0); end function RetroSnaker:CreateTimeFrameCall(Second) local scheduler = cc.Director:getInstance():getScheduler() -- 根据设置每几秒调用这个函数 local function onTimerCallback(dt) self:UpdateTimer(dt) end self.schedulerID = scheduler:scheduleScriptFunc( function(dt) onTimerCallback(dt) end , Second, false) end function RetroSnaker:CreateKeyEvent() local function OnKeyPressed(KeyCode, Event) self:OnKeyPressed(KeyCode, Event) end local function OnKeyReleased(KeyCode, Event) self:OnKeyReleased(KeyCode, Event) end local Listener = cc.EventListenerKeyboard:create(); Listener:registerScriptHandler(OnKeyPressed, cc.Handler.EVENT_KEYBOARD_PRESSED); Listener:registerScriptHandler(OnKeyReleased, cc.Handler.EVENT_KEYBOARD_RELEASED); cc.Director:getInstance():getEventDispatcher():addEventListenerWithSceneGraphPriority(Listener, self); end return RetroSnaker; ]] -- Gobang --[[ 横向:两边同时索引,索引到相同的var++,如果var == 4则win,不超过4,var = 0,再右边或者左边进行索引, if(var == 4) { win; } { int Map[10][10] = { 0 }; int X = 0; int Y = 0; int WinState = 0; for (int i = 0; i < 2; i++) { if (Map[Y][X + i + 1] == 666) { WinState++; } if(Map[Y][X - i - 1] == 666) { WinState++; } } if (WinState == 4) { // return;赢 } else { WinState = 0; //左边 for (int i = 0; i < 5; i++) { if (Map[Y][X - i - 1] == 666) { WinState++; } } if (WinState == 4) { //return;赢 } else//左边不行右边 { //右边 for (int i = 0; i < 5; i++) { if (Map[Y][X + i + 1] == 666) { WinState++; } } if (WinState == 4) { //return;赢 } } } } ]]