1. 程式人生 > >Cocos2d-x 3.2 Lua示例 ClickAndMoveTest(點選移動測試)

Cocos2d-x 3.2 Lua示例 ClickAndMoveTest(點選移動測試)

--[[
ClickAndMoveTest.lua
點選與移動
]]--

-- 獲取螢幕尺寸
local size = cc.Director:getInstance():getWinSize()
local layer = nil -- 層
local kTagSprite = 1 --精靈標記

local function initWithLayer()
    local sprite = cc.Sprite:create(s_pPathGrossini)


    -- 新增顏色層,黃色
    local bgLayer = cc.LayerColor:create(cc.c4b(255,255,0,255))
    layer:addChild(bgLayer, -1)
    
    -- 新增
    layer:addChild(sprite, 0, kTagSprite)
    -- 設定精靈位置到(20,150)
    sprite:setPosition(cc.p(20,150))
    -- 執行跳的動作,第一個引數為持續時間,第二個引數為位置,第三個引數為跳的高度,第四個引數跳的次數  
    sprite:runAction(cc.JumpTo:create(4, cc.p(300,48), 100, 4))

    -- 背景層執行無限重複的動作序列,先淡進,再淡出
    bgLayer:runAction(cc.RepeatForever:create(cc.Sequence:create(
                                                 cc.FadeIn:create(1),
                                                 cc.FadeOut:create(1))))

    -- 觸控開始
    local function onTouchBegan(touch, event)
        return true
    end

    -- 觸控結束
    local function onTouchEnded(touch, event)
        -- 獲取點選位置
        local location = touch:getLocation()
        
        -- 根據標記獲取子節點
        local s = layer:getChildByTag(kTagSprite)
        s:stopAllActions()-- 停止所有動作
        -- 執行移動動作,移動到點選的位置
        s:runAction(cc.MoveTo:create(1, cc.p(location.x, location.y)))
        local posX, posY = s:getPosition() -- 獲取精靈的位置
        local o = location.x - posX -- X軸的距離
        local a = location.y - posY -- Y軸的距離
        local at = math.atan(o / a) / math.pi * 180.0 --求角度 ,反正切函式求弧度/π*180.0
        --1弧度= 180/π, 1度=π/180

        -- 點選位置在下邊
        if a < 0 then
            -- 點選位置在左邊
            if o < 0 then
                at = 180 + math.abs(at)
            else
            -- 點選位置在右邊
                at = 180 - math.abs(at)
            end
        end
        -- 執行旋轉的動作
        s:runAction(cc.RotateTo:create(1, at))
    end


    -- 單點觸控的監聽器
    local listener = cc.EventListenerTouchOneByOne:create()
    -- 註冊兩個回撥監聽方法
    listener:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN )
    listener:registerScriptHandler(onTouchEnded,cc.Handler.EVENT_TOUCH_ENDED )
    local eventDispatcher = layer:getEventDispatcher()-- 時間派發器
    -- 繫結觸控事件到層當中
    eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layer)

    return layer
end

--------------------------------
-- Click And Move Test
--------------------------------
function ClickAndMoveTest()
    cclog("ClickAndMoveTest")
    local scene = cc.Scene:create()
    layer = cc.Layer:create()

    initWithLayer()
    scene:addChild(layer)
    scene:addChild(CreateBackMenuItem())
    

    return scene
end