cocos2d-lua仿写cocos2d-x HelloWorld

这篇博客介绍了如何用lua脚本来实现cocos2d-x HelloWorld程序。主要内容包括lua环境的设置、创建动画、处理触摸事件以及播放背景音乐和音效。通过创建狗的移动和农场背景的交互,展示了cocos2d-lua的基本应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


今天开始敲lua的代码 

lua的自带的跟-x的不一样

所以就想找回熟悉的感觉


以下是hello.lua的重写


-- for CCLuaEngine traceback

function __G__TRACKBACK__(msg)

    print("----------------------------------------")

    print("LUA ERROR: " .. tostring(msg) .. "\n")

    print(debug.traceback())

    print("----------------------------------------")

end


local function main()

    -- avoid memory leak

    collectgarbage("setpause", 100)

    collectgarbage("setstepmul", 5000)


    local cclog = function(...)

        print(string.format(...))

    end


    require "hello2"                                                         -- 包含hello2这个脚本

    cclog("result is " .. myadd(3, 5))                                       -- output 输出result is 8


    ---------------


    local visibleSize = CCDirector:sharedDirector():getVisibleSize()         --  获取屏幕(可视)大小

    local origin = CCDirector:sharedDirector():getVisibleOrigin()            --  获取屏幕原点

    

    cclog("width is %d,height is %d",visibleSize.width,visibleSize.height)


    -- add the moving dog

    local function creatDog()

        local frameWidth = 105

        local frameHeight = 95


        -- create dog animate                                                 --  创建小狐狸,不是小狗啊 帧动画

        local textureDog = CCTextureCache:sharedTextureCache():addImage("dog.png")

        local rect = CCRectMake(0, 0, frameWidth, frameHeight)

        local frame0 = CCSpriteFrame:createWithTexture(textureDog, rect)

        rect = CCRectMake(frameWidth, 0, frameWidth, frameHeight)

        local frame1 = CCSpriteFrame:createWithTexture(textureDog, rect)


        local spriteDog = CCSprite:createWithSpriteFrame(frame0)

        spriteDog.isPaused = false

        spriteDog:setPosition(visibleSize.width, origin.y + visibleSize.height / 4 * 3)


        local animFrames = CCArray:create()


        animFrames:addObject(frame0)

        animFrames:addObject(frame1)


        local animation = CCAnimation:createWithSpriteFrames(animFrames, 0.5)         --  设置一直换帧

        local animate = CCAnimate:create(animation);

        spriteDog:runAction(CCRepeatForever:create(animate))


        -- moving dog at every frame

        local function tick()

            if spriteDog.isPaused then return end                                     --  如果是暂停的就不动

            local x, y = spriteDog:getPosition()

            if    x<origin.x   then

              -- x > origin.x + visibleSize.width then

                  x=origin.x+visibleSize.width

               -- x = origin.x 

            else

                 x= x - 1                                           

                 --x = x + 1

            end


            spriteDog:setPositionX(x)

        end


        CCDirector:sharedDirector():getScheduler():scheduleScriptFunc(tick, 0, false)


        return spriteDog

    end


    -- create farm

    local function createLayerFarm()

        local layerFarm = CCLayer:create()


        -- add in farm background

        local bg = CCSprite:create("farm.jpg")

        bg:setPosition(origin.x + visibleSize.width / 2 + 80, origin.y + visibleSize.height / 2)

        layerFarm:addChild(bg)


        -- add land sprite

        for i = 0, 3 do

            for j = 0, 1 do

                local spriteLand = CCSprite:create("land.png")

                spriteLand:setPosition(200 + j * 180 - i % 2 * 90, 10 + i * 95 / 2)

                layerFarm:addChild(spriteLand)

            end

        end


        -- add crop

        local frameCrop = CCSpriteFrame:create("crop.png", CCRectMake(0, 0, 105, 95))

        for i = 0, 3 do

            for j = 0, 1 do

                local spriteCrop = CCSprite:createWithSpriteFrame(frameCrop);

                spriteCrop:setPosition(10 + 200 + j * 180 - i % 2 * 90, 30 + 10 + i * 95 / 2)

                layerFarm:addChild(spriteCrop)

            end

        end


        -- add moving dog

        local spriteDog = creatDog()

        layerFarm:addChild(spriteDog)


        -- handing touch events

        local touchBeginPoint = nil


        local function onTouchBegan(x, y)                                  --  触摸函数  参数直接是xy

            cclog("onTouchBegan: %0.2f, %0.2f", x, y)

            touchBeginPoint = {x = x, y = y}

            spriteDog.isPaused = true

            -- CCTOUCHBEGAN event must return true

            return true

        end


        local function onTouchMoved(x, y)

            cclog("onTouchMoved: %0.2f, %0.2f", x, y)

            if touchBeginPoint then

                local cx, cy = layerFarm:getPosition()

                layerFarm:setPosition(cx + x - touchBeginPoint.x,

                                      cy + y - touchBeginPoint.y)

                touchBeginPoint = {x = x, y = y}

            end

        end


        local function onTouchEnded(x, y)

            cclog("onTouchEnded: %0.2f, %0.2f", x, y)

            touchBeginPoint = nil

            spriteDog.isPaused = false

        end


        local function onTouch(eventType, x, y)

            if eventType == "began" then   

                return onTouchBegan(x, y)

            elseif eventType == "moved" then

                return onTouchMoved(x, y)

            else

                return onTouchEnded(x, y)

            end

        end


        layerFarm:registerScriptTouchHandler(onTouch)                     --  设置可以触摸

        layerFarm:setTouchEnabled(true)


        return layerFarm

    end



    -- create menu

    local function createLayerMenu()

        local layerMenu = CCLayer:create()


        local menuPopup, menuTools, effectID


        local function menuCallbackClosePopup()

            -- stop test sound effect

            SimpleAudioEngine:sharedEngine():stopEffect(effectID)

            menuPopup:setVisible(false)

        end


        local function menuCallbackOpenPopup()

            -- loop test sound effect

            local effectPath = CCFileUtils:sharedFileUtils():fullPathForFilename("effect1.wav")

            effectID = SimpleAudioEngine:sharedEngine():playEffect(effectPath)

            menuPopup:setVisible(true)

        end


        -- add a popup menu

        local menuPopupItem = CCMenuItemImage:create("menu2.png", "menu2.png")

        menuPopupItem:setPosition(0, 0)

        menuPopupItem:registerScriptTapHandler(menuCallbackClosePopup)

        menuPopup = CCMenu:createWithItem(menuPopupItem)

        menuPopup:setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2)

        menuPopup:setVisible(false)

        layerMenu:addChild(menuPopup)


        -- add the left-bottom "tools" menu to invoke menuPopup

        local menuToolsItem = CCMenuItemImage:create("menu1.png", "menu1.png")

        menuToolsItem:setPosition(0, 0)

        menuToolsItem:registerScriptTapHandler(menuCallbackOpenPopup)

        menuTools = CCMenu:createWithItem(menuToolsItem)

        local itemWidth = menuToolsItem:getContentSize().width

        local itemHeight = menuToolsItem:getContentSize().height

        menuTools:setPosition(origin.x + itemWidth/2, origin.y + itemHeight/2)

        layerMenu:addChild(menuTools)


        return layerMenu

    end


    -- play background music, preload effect


    -- uncomment below for the BlackBerry version

    -- local bgMusicPath = CCFileUtils:sharedFileUtils():fullPathForFilename("background.ogg")

    local bgMusicPath = CCFileUtils:sharedFileUtils():fullPathForFilename("background.mp3")

    SimpleAudioEngine:sharedEngine():playBackgroundMusic(bgMusicPath, true)

    local effectPath = CCFileUtils:sharedFileUtils():fullPathForFilename("effect1.wav")

    SimpleAudioEngine:sharedEngine():preloadEffect(effectPath)


    -- run

    local sceneGame = CCScene:create()

    sceneGame:addChild(createLayerFarm())

    sceneGame:addChild(createLayerMenu())

    CCDirector:sharedDirector():runWithScene(sceneGame)

end



xpcall(main, __G__TRACKBACK__)


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值