cocos2d x权威指南-x开发实例哪里比较全面?

欢迎大家访问游戏开发网,有您更美好!
请记住本站网址,一定要搜藏哦亲!
Cocos2d-x 3.2 Lua示例CocosDenshionTest(音频测试)详解
Cocos2d-x 3.2 Lua示例CocosDenshionTest(音频测试)详解
围观177次 评论关闭 编辑日期: 字体:
本篇博客介绍Cocos2d-x 3.2中Lua示例的音频测试,Cocos2d-x使用SimpleAudioEngine这个类来实现音频的控制,比如播放、暂停、停止等操作。
Lua代码中,使用的是AudioEngine,具体实现可以参考AudioEngine.lua文件,只是把SimpleAudioEngin进行了封装。
示例代码:
CocosDenshionTest.lua
Cocos2d-x 音频支持
require "AudioEngine"
local EFFECT_FILE = "effect1.wav"
local MUSIC_FILE = nil
-- 获取目标平台
local targetPlatform = cc.Application:getInstance():getTargetPlatform()
-- iphone或者ipad
if (cc.PLATFORM_OS_IPHONE == targetPlatform) or (cc.PLATFORM_OS_IPAD == targetPlatform) then
MUSIC_FILE = "background.caf" -- caf格式
MUSIC_FILE = "background.mp3" -- mp3格式
local LINE_SPACE = 40
local function CocosDenshionTest()
local ret = cc.Layer:create()
local m_pItmeMenu = nil
local m_tBeginPos = cc.p(0, 0)
local m_nSoundId = 0
-- 测试菜单项
local testItems = {
"play background music",
"stop background music",
"pause background music",
"resume background music",
"rewind background music",
"is background music playing",
"play effect",
"play effect repeatly",
"stop effect",
"unload effect",
"add background music volume",
"sub background music volume",
"add effects volume",
"sub effects volume",
"pause effect",
"resume effect",
"pause all effects",
"resume all effects",
"stop all effects"
-- 菜单回调方法
local function menuCallback(tag, pMenuItem)
local nIdx = pMenuItem:getLocalZOrder() - 10000
-- play background music
if nIdx ==
AudioEngine.playMusic(MUSIC_FILE, true) -- 播放音乐
elseif nIdx == 1 then
-- stop background music
AudioEngine.stopMusic()
-- 停止背景音乐
elseif nIdx == 2 then
-- pause background music
AudioEngine.pauseMusic() -- 暂停音乐
elseif nIdx == 3 then
-- resume background music
AudioEngine.resumeMusic() -- 继续播放音乐
-- rewind background music
elseif nIdx == 4 then
AudioEngine.rewindMusic()
-- 循环播放
elseif nIdx == 5 then
-- is background music playing
if AudioEngine.isMusicPlaying () then -- 音乐正在播放
cclog("background music is playing")
cclog("background music is not playing")
elseif nIdx == 6 then
-- play effect
m_nSoundId = AudioEngine.playEffect(EFFECT_FILE)
-- 播放音效
elseif nIdx == 7 then
-- play effect
m_nSoundId = AudioEngine.playEffect(EFFECT_FILE, true) -- 播放音效,第二个参数表示是否循环,true表示循环
elseif nIdx == 8 then
-- stop effect
AudioEngine.stopEffect(m_nSoundId) -- 停止音效
elseif nIdx == 9 then
-- unload effect
AudioEngine.unloadEffect(EFFECT_FILE)
-- 不加载音效
elseif nIdx == 10 then
-- add bakcground music volume
AudioEngine.setMusicVolume(AudioEngine.getMusicVolume() + 0.1) -- 增加音量
elseif nIdx == 11 then
-- sub backgroud music volume
AudioEngine.setMusicVolume(AudioEngine.getMusicVolume() - 0.1) -- 减小音量
elseif nIdx == 12 then
-- add effects volume
AudioEngine.setEffectsVolume(AudioEngine.getEffectsVolume() + 0.1) -- 增加音效音量
elseif nIdx == 13 then
-- sub effects volume
AudioEngine.setEffectsVolume(AudioEngine.getEffectsVolume() - 0.1) -- 减少音效音量
elseif nIdx == 14 then
AudioEngine.pauseEffect(m_nSoundId)
-- 暂停音效
elseif nIdx == 15 then
AudioEngine.resumeEffect(m_nSoundId) -- 恢复音效
elseif nIdx == 16 then
AudioEngine.pauseAllEffects() -- 暂停所有音效
elseif nIdx == 17 then
AudioEngine.resumeAllEffects() -- 恢复所有音效
elseif nIdx == 18 then
AudioEngine.stopAllEffects() -- 停止所有音效
-- add menu items for tests
m_pItmeMenu = cc.Menu:create() -- 创建菜单
m_nTestCount = table.getn(testItems)
local i = 1
i = 1, m_nTestCount do
label = cc.Label:createWithTTF(testItems[i], s_arialPath, 24)
label:setAnchorPoint(cc.p(0.5, 0.5))
pMenuItem = cc.MenuItemLabel:create(label) -- 菜单标签
pMenuItem:registerScriptTapHandler(menuCallback) -- 注册菜单回调方法
m_pItmeMenu:addChild(pMenuItem, i + 10000 -1)
pMenuItem:setPosition( cc.p( VisibleRect:center().x, (VisibleRect:top().y - i * LINE_SPACE) ))
-- 设置菜单内容大小
m_pItmeMenu:setContentSize(cc.size(VisibleRect:getVisibleRect().width, (m_nTestCount + 1) * LINE_SPACE))
m_pItmeMenu:setPosition(cc.p(0, 0))
ret:addChild(m_pItmeMenu)
-- preload background music and effect
AudioEngine.preloadMusic( MUSIC_FILE ) -- 预加载音乐
AudioEngine.preloadEffect( EFFECT_FILE ) -- 预加载音效
-- set default volume
AudioEngine.setEffectsVolume(0.5) -- 设置音效音量
AudioEngine.setMusicVolume(0.5) -- 设置音乐音量
local function onNodeEvent(event)
if event == "enter" then -- 进来时
elseif event == "exit" then --
AudioEngine.destroyInstance() -- 销毁对象
-- 注册层的结点事件
ret:registerScriptHandler(onNodeEvent)
local prev = {x = 0, y = 0}
local function onTouchEvent(eventType, x, y)
if eventType == "began" then -- 开始点击
prev.x = x
prev.y = y
m_tBeginPos = cc.p(x, y) -- 开始点击位置
return true
eventType == "moved" then -- 移动事件
local touchLocation = cc.p(x, y) -- 获取触摸的位置
local nMoveY = touchLocation.y - m_tBeginPos.y -- 触摸位置减去开始位置等于移动的距离
local curPosX, curPosY = m_pItmeMenu:getPosition() -- 获取当前菜单的位置
local curPos = cc.p(curPosX, curPosY) --
local nextPos = cc.p(curPos.x, curPos.y + nMoveY) -- 下一个位置
if nextPos.y & 0.0 then
m_pItmeMenu:setPosition(cc.p(0, 0))
if nextPos.y & ((m_nTestCount + 1)* LINE_SPACE - VisibleRect:getVisibleRect().height) then
m_pItmeMenu:setPosition(cc.p(0, ((m_nTestCount + 1)* LINE_SPACE - VisibleRect:getVisibleRect().height)))
m_pItmeMenu:setPosition(nextPos)
m_tBeginPos.x = touchLocation.x
-- 重新记录开始位置
m_tBeginPos.y = touchLocation.y
prev.x = x
prev.y = y
-- 触摸开始回调方法
local function onTouchBegan(touch, event)
local location = touch:getLocation()
prev.x = location.x
prev.y = location.y
m_tBeginPos = location
return true
-- 触摸移动的回调方法
local function onTouchMoved(touch, event)
local location = touch:getLocation()
local touchLocation = location
local nMoveY = touchLocation.y - m_tBeginPos.y
local curPosX, curPosY = m_pItmeMenu:getPosition()
local curPos = cc.p(curPosX, curPosY)
local nextPos = cc.p(curPos.x, curPos.y + nMoveY)
if nextPos.y & 0.0 then
m_pItmeMenu:setPosition(cc.p(0, 0))
if nextPos.y & ((m_nTestCount + 1)* LINE_SPACE - VisibleRect:getVisibleRect().height) then
m_pItmeMenu:setPosition(cc.p(0, ((m_nTestCount + 1)* LINE_SPACE - VisibleRect:getVisibleRect().height)))
m_pItmeMenu:setPosition(nextPos)
m_tBeginPos.x = touchLocation.x
m_tBeginPos.y = touchLocation.y
prev.x = location.x
prev.y = location.y
-- 单点触摸
local listener = cc.EventListenerTouchOneByOne:create()
listener:setSwallowTouches(true)
-- 注册脚本监听事件
listener:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN )
listener:registerScriptHandler(onTouchMoved,cc.Handler.EVENT_TOUCH_MOVED )
local eventDispatcher = ret:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, ret)
return ret
function CocosDenshionTestMain()
cclog("CocosDenshionTestMain")
local scene = cc.Scene:create()
scene:addChild(CocosDenshionTest())
scene:addChild(CreateBackMenuItem())
return scene
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
--[[CocosDenshionTest.luaCocos2d-x 音频支持]]--require "AudioEngine"local EFFECT_FILE = "effect1.wav" &local MUSIC_FILE = nil-- 获取目标平台local targetPlatform = cc.Application:getInstance():getTargetPlatform()-- iphone或者ipadif (cc.PLATFORM_OS_IPHONE == targetPlatform) or (cc.PLATFORM_OS_IPAD == targetPlatform) then&&MUSIC_FILE = "background.caf" -- caf格式else&&MUSIC_FILE = "background.mp3" -- mp3格式end&local LINE_SPACE = 40 &local function CocosDenshionTest()&&local ret = cc.Layer:create()&&local m_pItmeMenu = nil&&local m_tBeginPos = cc.p(0, 0)&&local m_nSoundId = 0&&&-- 测试菜单项&&local testItems = {&&&&"play background music",&&&&"stop background music",&&&&"pause background music",&&&&"resume background music",&&&&"rewind background music",&&&&"is background music playing",&&&&"play effect",&&&&"play effect repeatly",&&&&"stop effect",&&&&"unload effect",&&&&"add background music volume",&&&&"sub background music volume",&&&&"add effects volume",&&&&"sub effects volume",&&&&"pause effect",&&&&"resume effect",&&&&"pause all effects",&&&&"resume all effects",&&&&"stop all effects"&&}&&&-- 菜单回调方法&&local function menuCallback(tag, pMenuItem)&&&&local nIdx = pMenuItem:getLocalZOrder() - 10000&&&&-- play background music&&&&if nIdx ==&&0 then&&&&&&AudioEngine.playMusic(MUSIC_FILE, true) -- 播放音乐&&&&elseif nIdx == 1 then&&&&&&-- stop background music&&&&&&AudioEngine.stopMusic()&&-- 停止背景音乐&&&&elseif nIdx == 2 then&&&&&&-- pause background music&&&&&&AudioEngine.pauseMusic() -- 暂停音乐&&&&elseif nIdx == 3 then&&&&&&-- resume background music&&&&&&AudioEngine.resumeMusic() -- 继续播放音乐&&&&&&-- rewind background music&&&&elseif nIdx == 4 then&&&&&&AudioEngine.rewindMusic()&&-- 循环播放&&&&elseif nIdx == 5 then&&&&&&-- is background music playing&&&&&&if AudioEngine.isMusicPlaying () then -- 音乐正在播放&&&&&&&&cclog("background music is playing")&&&&&&else&&&&&&&&cclog("background music is not playing")&&&&&&end&&&&elseif nIdx == 6 then&&&&&&-- play effect&&&&&&m_nSoundId = AudioEngine.playEffect(EFFECT_FILE)&& -- 播放音效&&&&elseif nIdx == 7 then&&&&&&-- play effect&&&&&&m_nSoundId = AudioEngine.playEffect(EFFECT_FILE, true) -- 播放音效,第二个参数表示是否循环,true表示循环&&&&elseif nIdx == 8 then&&&&&&-- stop effect&&&&&&AudioEngine.stopEffect(m_nSoundId) -- 停止音效&&&&elseif nIdx == 9 then&&&&&&-- unload effect&&&&&&AudioEngine.unloadEffect(EFFECT_FILE)&&-- 不加载音效&&&&elseif nIdx == 10 then&&&&&&-- add bakcground music volume&&&&&&AudioEngine.setMusicVolume(AudioEngine.getMusicVolume() + 0.1) -- 增加音量&&&&elseif nIdx == 11 then&&&&&&-- sub backgroud music volume&&&&&&AudioEngine.setMusicVolume(AudioEngine.getMusicVolume() - 0.1) -- 减小音量&&&&elseif nIdx == 12 then&&&&&&-- add effects volume&&&&&&AudioEngine.setEffectsVolume(AudioEngine.getEffectsVolume() + 0.1) -- 增加音效音量&&&&elseif nIdx == 13 then&&&&&&-- sub effects volume&&&&&&AudioEngine.setEffectsVolume(AudioEngine.getEffectsVolume() - 0.1) -- 减少音效音量&&&&elseif nIdx == 14 then&&&&&&AudioEngine.pauseEffect(m_nSoundId)&&-- 暂停音效&&&&elseif nIdx == 15 then&&&&&&AudioEngine.resumeEffect(m_nSoundId) -- 恢复音效&&&&elseif nIdx == 16 then&&&&&&AudioEngine.pauseAllEffects() -- 暂停所有音效&&&&elseif nIdx == 17 then&&&&&&AudioEngine.resumeAllEffects() -- 恢复所有音效&&&&elseif nIdx == 18 then&&&&&&AudioEngine.stopAllEffects() -- 停止所有音效&&&&end&&end&&-- add menu items for tests&&m_pItmeMenu = cc.Menu:create() -- 创建菜单&&&m_nTestCount = table.getn(testItems)&&local i = 1&&for&&i = 1, m_nTestCount do&&&&local&&label = cc.Label:createWithTTF(testItems[i], s_arialPath, 24)&&&&label:setAnchorPoint(cc.p(0.5, 0.5))&&&&local&&pMenuItem = cc.MenuItemLabel:create(label) -- 菜单标签&&&&pMenuItem:registerScriptTapHandler(menuCallback) -- 注册菜单回调方法&&&&m_pItmeMenu:addChild(pMenuItem, i + 10000 -1)&&&&pMenuItem:setPosition( cc.p( VisibleRect:center().x, (VisibleRect:top().y - i * LINE_SPACE) ))&&end&&&-- 设置菜单内容大小&&m_pItmeMenu:setContentSize(cc.size(VisibleRect:getVisibleRect().width, (m_nTestCount + 1) * LINE_SPACE))&&m_pItmeMenu:setPosition(cc.p(0, 0))&&ret:addChild(m_pItmeMenu)&&&-- preload background music and effect&&AudioEngine.preloadMusic( MUSIC_FILE ) -- 预加载音乐&&AudioEngine.preloadEffect( EFFECT_FILE ) -- 预加载音效&&&-- set default volume&&AudioEngine.setEffectsVolume(0.5) -- 设置音效音量&&AudioEngine.setMusicVolume(0.5) -- 设置音乐音量&&&local function onNodeEvent(event)&&&&if event == "enter" then -- 进来时&&&&&&elseif event == "exit" then --&&退出时&&&&&&AudioEngine.destroyInstance() -- 销毁对象&&&&end&&end&&&-- 注册层的结点事件&&ret:registerScriptHandler(onNodeEvent)&&&local prev = {x = 0, y = 0}&&local function onTouchEvent(eventType, x, y)&&&&if eventType == "began" then -- 开始点击&&&&&&prev.x = x&&&&&&prev.y = y&&&&&&m_tBeginPos = cc.p(x, y) -- 开始点击位置&&&&&&return true&&&&elseif&&eventType == "moved" then -- 移动事件&&&&&&local touchLocation = cc.p(x, y) -- 获取触摸的位置&&&&&&local nMoveY = touchLocation.y - m_tBeginPos.y -- 触摸位置减去开始位置等于移动的距离&&&&&&local curPosX, curPosY = m_pItmeMenu:getPosition() -- 获取当前菜单的位置&&&&&&local curPos = cc.p(curPosX, curPosY) --&&当前位置&&&&&&local nextPos = cc.p(curPos.x, curPos.y + nMoveY) -- 下一个位置&&&&&&&if nextPos.y < 0.0 then&&&&&&&&m_pItmeMenu:setPosition(cc.p(0, 0))&&&&&&end&&&&&&&if nextPos.y > ((m_nTestCount + 1)* LINE_SPACE - VisibleRect:getVisibleRect().height) then&&&&&&&&m_pItmeMenu:setPosition(cc.p(0, ((m_nTestCount + 1)* LINE_SPACE - VisibleRect:getVisibleRect().height)))&&&&&&end&&&&&&&m_pItmeMenu:setPosition(nextPos)&&&&&&m_tBeginPos.x = touchLocation.x&&-- 重新记录开始位置&&&&&&m_tBeginPos.y = touchLocation.y&&&&&&&prev.x = x&&&&&&prev.y = y&&&&end&&end&&&-- 触摸开始回调方法&&local function onTouchBegan(touch, event)&&&&local location = touch:getLocation()&&&&prev.x = location.x&&&&prev.y = location.y&&&&m_tBeginPos = location&&&&return true&&end&&&-- 触摸移动的回调方法&&local function onTouchMoved(touch, event)&&&&local location = touch:getLocation()&&&&local touchLocation = location&&&&local nMoveY = touchLocation.y - m_tBeginPos.y&&&&local curPosX, curPosY = m_pItmeMenu:getPosition()&&&&local curPos = cc.p(curPosX, curPosY)&&&&local nextPos = cc.p(curPos.x, curPos.y + nMoveY)&&&&&if nextPos.y < 0.0 then&&&&&&m_pItmeMenu:setPosition(cc.p(0, 0))&&&&end&&&&&if nextPos.y > ((m_nTestCount + 1)* LINE_SPACE - VisibleRect:getVisibleRect().height) then&&&&&&m_pItmeMenu:setPosition(cc.p(0, ((m_nTestCount + 1)* LINE_SPACE - VisibleRect:getVisibleRect().height)))&&&&end&&&&&m_pItmeMenu:setPosition(nextPos)&&&&m_tBeginPos.x = touchLocation.x&&&&m_tBeginPos.y = touchLocation.y&&&&&prev.x = location.x&&&&prev.y = location.y&&end&&&-- 单点触摸&&local listener = cc.EventListenerTouchOneByOne:create()&&listener:setSwallowTouches(true)&&-- 注册脚本监听事件&&listener:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN )&&listener:registerScriptHandler(onTouchMoved,cc.Handler.EVENT_TOUCH_MOVED )&&local eventDispatcher = ret:getEventDispatcher()&&eventDispatcher:addEventListenerWithSceneGraphPriority(listener, ret)&&&return retend&function CocosDenshionTestMain()&&cclog("CocosDenshionTestMain")&&local scene = cc.Scene:create()&&scene:addChild(CocosDenshionTest())&&scene:addChild(CreateBackMenuItem())&&return sceneend
本文固定链接:
转载请注明:
作者:游戏开发
欢迎大家访问游戏开发网!
如果您觉得这篇文章有用处,请支持作者!鼓励作者写出更好更多的文章!
您可能还会对这些文章感兴趣!Cocos2d-x系统开发在哪里学比较好,有没有学过的朋友?_百度知道
Cocos2d-x系统开发在哪里学比较好,有没有学过的朋友?
提问者采纳
我男朋友是在麦子学院学习的,他以前是做IOS开发的,学习了三个多月,现在找了个游戏开发的护户份较莓记逢席抚芦工作,感谢麦子学院。
提问者评价
其他类似问题
cocos2d的相关知识
等待您来回答
下载知道APP
随时随地咨询
出门在外也不愁欢迎大家访问游戏开发网,有您更美好!
请记住本站网址,一定要搜藏哦亲!
Cocos2d-x 3.2 Lua示例 AssetsManagerTest(资源管理器)使用详解
Cocos2d-x 3.2 Lua示例 AssetsManagerTest(资源管理器)使用详解
围观391次 评论关闭 编辑日期: 字体:
本篇博客介绍Cocos2d-x 为我们提供的一个类——AssetsManager在Lua中的使用例子,效果如下图:
Cocos2d-x 给出的例子是AssetsManagerTest,进入会发现三个菜单项:
enter是进入场景,reset是删除本地版本,重新设置,update就是更新资源文件。
笔者使用LDT打开lua-tests测试项目:
在src目录下找到AssetsManagerTest目录,查看以下代码(笔者对其进行了注释):
&&&AsetsManagerModule.lua
资源管理器模块
local AssetManagerModule = {}
function AssetManagerModule.newScene(backfunc)
-- 获取屏幕大小
local winSize = cc.Director:getInstance():getWinSize()
-- 创建新的场景
local newScene = cc.Scene:create()
-- 创建新的层
local layer
= cc.Layer:create()
-- 后台更新
local function backToUpdate()
local scene = backfunc()
if scene ~= nil then
cc.Director:getInstance():replaceScene(scene)
-- 创建回退菜单
cc.MenuItemFont:setFontName("Arial")
cc.MenuItemFont:setFontSize(24)
local backMenuItem = cc.MenuItemFont:create("Back")
-- 放置在右下角大致的位置
backMenuItem:setPosition(cc.p(VisibleRect:rightBottom().x - 50, VisibleRect:rightBottom().y + 25))
-- 注册监听方法
backMenuItem:registerScriptTapHandler(backToUpdate)
-- 创建菜单
local backMenu = cc.Menu:create()
backMenu:setPosition(0, 0)
backMenu:addChild(backMenuItem)
layer:addChild(backMenu,6)
-- 创建标签
local helloLabel =
cc.Label:createWithTTF("Hello World", s_arialPath, 38)
helloLabel:setAnchorPoint(cc.p(0.5, 0.5))-- 锚点居中
helloLabel:setPosition(cc.p(winSize.width / 2, winSize.height - 40))
layer:addChild(helloLabel, 5)
-- 创建精灵,这里是一张背景图
local sprite = cc.Sprite:create("Images/background.png")
sprite:setAnchorPoint(cc.p(0.5, 0.5))-- 锚点居中
sprite:setPosition(cc.p(winSize.width / 2, winSize.height / 2))
layer:addChild(sprite, 0)
newScene:addChild(layer)-- 添加到场景
cc.Director:getInstance():replaceScene(newScene)-- 替换场景
-- 返回模块
return AssetManagerModule
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
--[[资源管理器模块]]--local AssetManagerModule = {}&--[[&&newScene]]--function AssetManagerModule.newScene(backfunc)&&&-- 获取屏幕大小&&local winSize = cc.Director:getInstance():getWinSize()&&&-- 创建新的场景&&local newScene = cc.Scene:create()&&-- 创建新的层&&local layer&&&&= cc.Layer:create()&&&-- 后台更新&&local function backToUpdate()&&&&local scene = backfunc()&&&&if scene ~= nil then&&&&&&cc.Director:getInstance():replaceScene(scene)&&&&end&&end&&&-- 创建回退菜单&&cc.MenuItemFont:setFontName("Arial")&&cc.MenuItemFont:setFontSize(24)&&local backMenuItem = cc.MenuItemFont:create("Back")&&-- 放置在右下角大致的位置&&backMenuItem:setPosition(cc.p(VisibleRect:rightBottom().x - 50, VisibleRect:rightBottom().y + 25))&&-- 注册监听方法&&backMenuItem:registerScriptTapHandler(backToUpdate)&&&-- 创建菜单&&local backMenu = cc.Menu:create()&&backMenu:setPosition(0, 0)&&backMenu:addChild(backMenuItem)&&layer:addChild(backMenu,6)&&&-- 创建标签&&local helloLabel =&&cc.Label:createWithTTF("Hello World", s_arialPath, 38)&&helloLabel:setAnchorPoint(cc.p(0.5, 0.5))-- 锚点居中&&helloLabel:setPosition(cc.p(winSize.width / 2, winSize.height - 40))&&layer:addChild(helloLabel, 5)&&&-- 创建精灵,这里是一张背景图&&local sprite = cc.Sprite:create("Images/background.png")&&sprite:setAnchorPoint(cc.p(0.5, 0.5))-- 锚点居中&&sprite:setPosition(cc.p(winSize.width / 2, winSize.height / 2))&&layer:addChild(sprite, 0)&&&newScene:addChild(layer)-- 添加到场景&&cc.Director:getInstance():replaceScene(newScene)-- 替换场景end&&-- 返回模块return AssetManagerModule
&&&AssetsManagerTest.lua
-- 获取目标平台
local targetPlatform = cc.Application:getInstance():getTargetPlatform()
local lineSpace = 40 -- 行间距
local itemTagBasic = 1000
local menuItemNames =
-- 获取屏幕大小
local winSize = cc.Director:getInstance():getWinSize()
local function updateLayer()
-- 首先创建一个层
local layer = cc.Layer:create()
local support
-- 判断是否支持iphone、ipad、win32、android或者mac
if (cc.PLATFORM_OS_IPHONE == targetPlatform) or (cc.PLATFORM_OS_IPAD == targetPlatform)
or (cc.PLATFORM_OS_WINDOWS == targetPlatform) or (cc.PLATFORM_OS_ANDROID == targetPlatform)
or (cc.PLATFORM_OS_MAC
== targetPlatform) then
support = true
-- 如果不支持平台
if not support then
print("Platform is not supported!")
return layer
local isUpdateItemClicked = false -- 是否更新项被点击
local assetsManager
= nil -- 资源管理器对象
local pathToSave
-- 保存路径
local menu = cc.Menu:create() -- 菜单
menu:setPosition(cc.p(0, 0))
-- 设置菜单位置
cc.MenuItemFont:setFontName("Arial")-- 设置菜单字体样式
cc.MenuItemFont:setFontSize(24) -- 设置字体大小
-- 用于更新的标签
local progressLable = cc.Label:createWithTTF("",s_arialPath,30)
progressLable:setAnchorPoint(cc.p(0.5, 0.5))
progressLable:setPosition(cc.p(140,50))
layer:addChild(progressLable)
-- 下载目录
pathToSave = createDownloadDir()
-- 下载错误回调
local function onError(errorCode)
-- 没有新版本
if errorCode == cc.ASSETSMANAGER_NO_NEW_VERSION then
progressLable:setString("no new version")
elseif errorCode == cc.ASSETSMANAGER_NETWORK then
-- 网络错误
progressLable:setString("network error")
-- 进度更新回调
local function onProgress( percent )
-- 显示下载进度
local progress = string.format("downloading %d%%",percent)
progressLable:setString(progress)
-- 下载成功方法回调
local function onSuccess()
progressLable:setString("downloading ok")
-- 获得资源管理器
local function getAssetsManager()
if nil == assetsManager then
-- 创建一个资源管理器,第一个参数是zip包下载地址,第二个参数是版本文件,第三个参数是保存路径
assetsManager = cc.AssetsManager:new("/samuele3hu/AssetsManagerTest/master/package.zip",
"/samuele3hu/AssetsManagerTest/master/version",
pathToSave)
-- 保留所有权,该方法会增加Ref对象的引用计数
assetsManager:retain()
-- 设置一系列委托
assetsManager:setDelegate(onError, cc.ASSETSMANAGER_PROTOCOL_ERROR )
assetsManager:setDelegate(onProgress, cc.ASSETSMANAGER_PROTOCOL_PROGRESS)
assetsManager:setDelegate(onSuccess, cc.ASSETSMANAGER_PROTOCOL_SUCCESS )
assetsManager:setConnectionTimeout(3)-- 设置连接超时
return assetsManager
local function update(sender)
progressLable:setString("")
-- 调用AssetsManager的update方法
getAssetsManager():update()
local function reset(sender)
progressLable:setString("")
-- 删除下载路径
deleteDownloadDir(pathToSave)
-- 删除版本
getAssetsManager():deleteVersion()
-- 创建下载路径
createDownloadDir()
-- 重新加载模块
local function reloadModule( moduleName )
package.loaded[moduleName] = nil
return require(moduleName)
local function enter(sender)
-- 如果更新按钮没有被点击
if not isUpdateItemClicked then
local realPath = pathToSave .. "/package"
addSearchPath(realPath,true)
-- 重新加载模块
assetsManagerModule = reloadModule("src/AssetsManagerTest/AssetsManagerModule")
assetsManagerModule.newScene(AssetsManagerTestMain)
-- 回调方法
local callbackFuncs =
-- 菜单回调方法
local function menuCallback(tag, menuItem)
local scene = nil
local nIdx = menuItem:getLocalZOrder() - itemTagBasic
local ExtensionsTestScene = CreateExtensionsTestScene(nIdx)
if nil ~= ExtensionsTestScene then
cc.Director:getInstance():replaceScene(ExtensionsTestScene)
-- 遍历添加三个菜单项
for i = 1, table.getn(menuItemNames) do
local item = cc.MenuItemFont:create(menuItemNames[i])
item:registerScriptTapHandler(callbackFuncs[i])-- 注册点击回调地址
-- 设置三个菜单的位置
item:setPosition(winSize.width / 2, winSize.height - i * lineSpace)
if not support then
item:setEnabled(false)
menu:addChild(item, itemTagBasic + i)
local function onNodeEvent(msgName)
if nil ~= assetsManager then
-- 释放资源
assetsManager:release()
assetsManager = nil
-- 注册层的点击回调方法
layer:registerScriptHandler(onNodeEvent)
layer:addChild(menu)
return layer
-------------------------------------
AssetsManager Test
-------------------------------------
function AssetsManagerTestMain()
local scene = cc.Scene:create()
scene:addChild(updateLayer())
scene:addChild(CreateBackMenuItem())
return scene
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
-- 获取目标平台local targetPlatform = cc.Application:getInstance():getTargetPlatform()&local lineSpace = 40 -- 行间距local itemTagBasic = 1000 local menuItemNames ={&&&&"enter",&&&&"reset",&&&&"update",}&-- 获取屏幕大小local winSize = cc.Director:getInstance():getWinSize()&-- 更新层local function updateLayer()&&&&-- 首先创建一个层&&&&local layer = cc.Layer:create()&&&&&local support&&= false&&&&-- 判断是否支持iphone、ipad、win32、android或者mac&&&&if (cc.PLATFORM_OS_IPHONE == targetPlatform) or (cc.PLATFORM_OS_IPAD == targetPlatform) &&&&&&&&or (cc.PLATFORM_OS_WINDOWS == targetPlatform) or (cc.PLATFORM_OS_ANDROID == targetPlatform) &&&&&&&&or (cc.PLATFORM_OS_MAC&&== targetPlatform) then&&&&&&&&support = true&&&&end&&&&&-- 如果不支持平台&&&&if not support then&&&&&&&&print("Platform is not supported!")&&&&&&&&return layer&&&&end&&&&&local isUpdateItemClicked = false -- 是否更新项被点击&&&&local assetsManager&&&&&& = nil -- 资源管理器对象&&&&local pathToSave&&&&&&&&&&= ""&&-- 保存路径&&&&&local menu = cc.Menu:create() -- 菜单&&&&menu:setPosition(cc.p(0, 0))&&-- 设置菜单位置&&&&cc.MenuItemFont:setFontName("Arial")-- 设置菜单字体样式&&&&cc.MenuItemFont:setFontSize(24) -- 设置字体大小&&&&&-- 用于更新的标签&&&&local progressLable = cc.Label:createWithTTF("",s_arialPath,30)&&&&progressLable:setAnchorPoint(cc.p(0.5, 0.5))&&&&progressLable:setPosition(cc.p(140,50))&&&&layer:addChild(progressLable)&&&&&-- 下载目录&&&&pathToSave = createDownloadDir()&&&&&-- 下载错误回调&&&&local function onError(errorCode)&&&&&&&&-- 没有新版本&&&&&&&&if errorCode == cc.ASSETSMANAGER_NO_NEW_VERSION then&&&&&&&&&&&&progressLable:setString("no new version")&&&&&&&&elseif errorCode == cc.ASSETSMANAGER_NETWORK then&&&&&&&&&&&&-- 网络错误&&&&&&&&&&&&progressLable:setString("network error")&&&&&&&&end&&&&end&&&&&-- 进度更新回调&&&&local function onProgress( percent )&&&&&&&&-- 显示下载进度&&&&&&&&local progress = string.format("downloading %d%%",percent)&&&&&&&&progressLable:setString(progress)&&&&end&&&&&&&&-- 下载成功方法回调&&&&local function onSuccess()&&&&&&&&progressLable:setString("downloading ok")&&&&end&&&&&&-- 获得资源管理器&&&&local function getAssetsManager()&&&&&&&&if nil == assetsManager then&&&&&&&&&&&&-- 创建一个资源管理器,第一个参数是zip包下载地址,第二个参数是版本文件,第三个参数是保存路径&&&&&&&&&&&&assetsManager = cc.AssetsManager:new("/samuele3hu/AssetsManagerTest/master/package.zip",&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& "/samuele3hu/AssetsManagerTest/master/version",&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& pathToSave)&&&&&&&&&&&&-- 保留所有权,该方法会增加Ref对象的引用计数&&&&&&&&&&&&assetsManager:retain()&&&&&&&&&&&&-- 设置一系列委托&&&&&&&&&&&&assetsManager:setDelegate(onError, cc.ASSETSMANAGER_PROTOCOL_ERROR )&&&&&&&&&&&&assetsManager:setDelegate(onProgress, cc.ASSETSMANAGER_PROTOCOL_PROGRESS)&&&&&&&&&&&&assetsManager:setDelegate(onSuccess, cc.ASSETSMANAGER_PROTOCOL_SUCCESS )&&&&&&&&&&&&assetsManager:setConnectionTimeout(3)-- 设置连接超时&&&&&&&&end&&&&&&&&&return assetsManager&&&&end&&&&&-- 更新&&&&local function update(sender)&&&&&&&&progressLable:setString("")&&&&&&&&-- 调用AssetsManager的update方法&&&&&&&&getAssetsManager():update()&&&&end&&&&&-- 重设&&&&local function reset(sender)&&&&&&&&progressLable:setString("")&&&&&&&&-- 删除下载路径&&&&&&&&deleteDownloadDir(pathToSave)&&&&&&&&&&&&&&&&-- 删除版本&&&&&&&&getAssetsManager():deleteVersion()&&&&&& &&&&&&&&-- 创建下载路径&&&&&&&&createDownloadDir()&&&&end&&&&&-- 重新加载模块&&&&local function reloadModule( moduleName )&&&&&&&&&package.loaded[moduleName] = nil&&&&&&&&&&&&&&return require(moduleName)&&&&end&&&&&&-- 进入&&&&local function enter(sender)&&&&&&&&-- 如果更新按钮没有被点击&&&&&&&&if not isUpdateItemClicked then&&&&&&&&&&&&local realPath = pathToSave .. "/package"&&&&&&&&&&&&addSearchPath(realPath,true)&&&&&&&&end&&&&&&&&&&&&&&&&-- 重新加载模块&&&&&&&&assetsManagerModule = reloadModule("src/AssetsManagerTest/AssetsManagerModule")&&&&&&&&&assetsManagerModule.newScene(AssetsManagerTestMain)&&&&end&&&&&-- 回调方法&&&&local callbackFuncs =&&&&{&&&&&&&&enter,&&&&&&&&reset,&&&&&&&&update,&&&&}&&&&&-- 菜单回调方法&&&&local function menuCallback(tag, menuItem)&&&&&&&&local scene = nil&&&&&&&&local nIdx = menuItem:getLocalZOrder() - itemTagBasic&&&&&&&&local ExtensionsTestScene = CreateExtensionsTestScene(nIdx)&&&&&&&&if nil ~= ExtensionsTestScene then&&&&&&&&&&&&cc.Director:getInstance():replaceScene(ExtensionsTestScene)&&&&&&&&end&&&&end&&&&&-- 遍历添加三个菜单项&&&&for i = 1, table.getn(menuItemNames) do&&&&&&&&local item = cc.MenuItemFont:create(menuItemNames[i])&&&&&&&&item:registerScriptTapHandler(callbackFuncs[i])-- 注册点击回调地址&&&&&&&&-- 设置三个菜单的位置&&&&&&&&item:setPosition(winSize.width / 2, winSize.height - i * lineSpace)&&&&&&&&if not support then&&&&&&&&&&&&item:setEnabled(false)&&&&&&&&end&&&&&&&&menu:addChild(item, itemTagBasic + i)&&&&end&&&&&local function onNodeEvent(msgName)&&&&&&&&if nil ~= assetsManager then&&&&&&&&&&&&-- 释放资源&&&&&&&&&&&&assetsManager:release()&&&&&&&&&&&&assetsManager = nil&&&&&&&&end&&&&end&&&&&-- 注册层的点击回调方法&&&&layer:registerScriptHandler(onNodeEvent)&&&&&&&&layer:addChild(menu)&&&&&return layerend&---------------------------------------&&AssetsManager Test-------------------------------------function AssetsManagerTestMain()&&&&local scene = cc.Scene:create()&&&&scene:addChild(updateLayer())&&&&scene:addChild(CreateBackMenuItem())&&&&return sceneend
以下这张图截自官网:
AssetsManager这个类为我们提供了以上这些方法,下面对这些方法逐个进行简单说明:
构造函数有三个参数:一个是zip下载地址,一个是版本文件网络地址,一个是下载保存路径。
checkStoragePath:检查存储路径
checkUpdate:检查更新,返回bool值
createDirectory:根据平台创建目录
deleteVersion:删除本地版本
downLoad:下载文件
downloadAndUncompress:下载并解压缩文件
getConnectionTimeout:获得连接超时时间
getDelegate:获得委托对象
getPackageUrl:获得压缩包地址
getStoragePath:获得存储地址
getVersion:获得版本号
getVersionFileUrl:获得版本文件地址
setConnectionTimeout:设置网络连接超时
setDelegate:设置委托
setPackageUrl:设置包路径
setSearchPath:设置优先资源搜索路径
setStoragePath:设置存储路径
setVersionFileUrl:设置版本文件路径
uncompress:解压缩文件
update:更新
这里还要介绍一个委托类:AssetsManagerDelegateProtocol,我们在实现下载更新时需要回调的三个方法:
读者可以稍微研读一下以上代码,这里Cocos2d-x只是给出一个简单使用AssetsManager对程序进行热更新的例子,但没有提供完整的解决方案。后面笔者也会对Lua对Cocos2d-x客户端进行热更新这部分进行研究,有机会跟大家分享一下这方面的知识。
本文固定链接:
转载请注明:
作者:游戏开发
欢迎大家访问游戏开发网!
如果您觉得这篇文章有用处,请支持作者!鼓励作者写出更好更多的文章!
您可能还会对这些文章感兴趣!

我要回帖

更多关于 cocos2d x下载 的文章

 

随机推荐