cocos2d-x lua 场景的创建

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))
	
	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

运行看看效果

相关文章

    本文实践自 RayWenderlich、Ali Hafizji 的文章《...
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@1...
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从C...
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发...
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《...
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试...