cocos2d-x lua 场景的创建

时间:2023-02-06 19:59:04

cocos2d-x lua中场景的创建,层的创建及菜单的回调和动画的简单使用

新建一个TestScene.lua

require "Cocos2d"
require "Cocos2dConstants"


--场景测试

local TestScene = class("TestScene",function ()

return cc.Scene:create()

end)

--创建一个场景类
function TestScene:createScene()

local scene = TestScene.new()

scene:addChild(scene:createLayer())

return scene

end


function TestScene:createLayer()

--创建一个层
local layer = cc.LayerColor:create(cc.c4b(255,255,255,255))

local visibleSize = cc.Director:getInstance():getVisibleSize()

--创建一个logo精灵
local logo = cc.Sprite:create("test/logo.png")
logo:setPosition(120,120)
layer:addChild(logo,1)


--加载plist资源文件
-- local cache = cc.SpriteFrameCache:getInstance():addSpriteFrames("test/hero.plist","test/hero.png")

local cache = cc.SpriteFrameCache:getInstance()
cache:addSpriteFrames("test/hero.plist","test/hero.png")

-- 创建一个英雄
local hero = cc.Sprite:createWithSpriteFrameName("hero_00.png")
hero:setPosition(150,200)
layer:addChild(hero,1)

--动画
local animFrames={}
for i=0,4 do

local frame = cache:getSpriteFrame(string.format("hero_%02d.png", i) )
animFrames[i] = frame

end

local animation = cc.Animation:createWithSpriteFrames(animFrames,0.1)
local animate = cc.Animate:create(animation)
--播放动画
hero:runAction(cc.RepeatForever:create(animate))



--菜单监听回调事件
local function testMenuCallback()
print("----点击了----")
end

local normalMenu = cc.MenuItemImage:create("test/normal.png","test/normal.png","test/normal.png")
normalMenu:setScale(0.5)
normalMenu:setPosition(0,100)
--注册菜单回调
normalMenu:registerScriptTapHandler(testMenuCallback)

--menu
local menu = cc.Menu:create(normalMenu)
layer:addChild(menu,1)


return layer

end

return TestScene


在main.lua中调用

local scene = require("TestScene")
local gameScene = scene:createScene()

if cc.Director:getInstance():getRunningScene() then
cc.Director:getInstance():replaceScene(gameScene)
else
cc.Director:getInstance():runWithScene(gameScene)
end

运行看看效果

cocos2d-x lua 场景的创建