cocos2d-x 3.2移动一张图片的demo

开发工具:Cocos Code IDE

代码实现:

require "Cocos2d"

-- cclog
local cclog = function(...)
    print(string.format(...))
end

-- for CCLuaEngine traceback
function __G__TRACKBACK__(msg)
    cclog("----------------------------------------")
    cclog("LUA ERROR: " .. tostring(msg) .. "\n")
    cclog(debug.traceback())
    cclog("----------------------------------------")
    return msg
end

local function setLayer(gameScene) 
    local layer = cc.Layer:create()
    layer:setAnchorPoint(0,0)
    gameScene:addChild(layer)
    return layer
end

---------------------------
--@return #Sprite image sprite
local function setImageSprite(layer)
    local sprite = cc.Sprite:create("dog.png")
    sprite:setPosition(200, 200)
    layer:addChild(sprite)
    return sprite
end

local function main()
    collectgarbage("collect")
    -- avoid memory leak
    collectgarbage("setpause", 100)
    collectgarbage("setstepmul", 5000)
    
    cc.FileUtils:getInstance():addSearchPath("src")
    cc.FileUtils:getInstance():addSearchPath("res")
    
    local gameScene = cc.Scene:create()
    
    local layer = setLayer(gameScene)
    
    local sprite = setImageSprite(layer)
    
    local touchBeginPoint = nil
    
    local function onTouchBegan(touch, event)
        local location = touch:getLocation()
        cclog("onTouchBegan: %0.2f, %0.2f", location.x, location.y)
        touchBeginPoint = {x=location.x, y=location.y}
        
        return true
    end 
    
    local function onTouchMoved(touch, event)
        local location = touch:getLocation()
        
        if touchBeginPoint then
            local cx, cy = sprite:getPosition()
        	sprite:setPosition(cx + location.x - touchBeginPoint.x,
                cy + location.y - touchBeginPoint.y)
        end
        touchBeginPoint = {x=location.x, y=location.y}
        
    end 
    
    local function onTouchEnded(touch, event)
        touchBeginPoint = nil
    end 
    
    local listener = cc.EventListenerTouchOneByOne:create()
    listener:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN )
    listener:registerScriptHandler(onTouchMoved,cc.Handler.EVENT_TOUCH_MOVED )
    listener:registerScriptHandler(onTouchEnded,cc.Handler.EVENT_TOUCH_ENDED )
    local eventDispatcher = sprite:getEventDispatcher()
    eventDispatcher:addEventListenerWithSceneGraphPriority(listener, sprite)
    
    cc.Director:getInstance():getOpenGLView():setDesignResolutionSize(480, 320, 0)
    
    if cc.Director:getInstance():getRunningScene() then
        cc.Director:getInstance():replaceScene(gameScene)
    else
        cc.Director:getInstance():runWithScene(gameScene)
    end
end


local status, msg = xpcall(main, __G__TRACKBACK__)
if not status then
    error(msg)
end


你可能感兴趣的:(cocos2d-x 3.2移动一张图片的demo)