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

運行看看效果



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章