1. 程式人生 > >Cocos2dx lua 橫向滾動字幕實現

Cocos2dx lua 橫向滾動字幕實現

需求:要求設計一個頂部滾動欄,滾動後臺推送的遊戲訊息文字。

要點:1、文字單行顯示;2、文字背景半透明黑色(寬度不是全屏的);

設計:可以使用ClippingNode來實現該功能。


UI設計如上圖所示。

程式碼實現:

--跑馬燈
function InputLayer:AddUibroadcastMsg()
    _Panel_Clipping = UIUtils:GetWidgetByName(_widget,{"Panel_Input", "Panel_MsgOut", "Panel_Clipping"})
    local Text_Msg =  UIUtils:GetWidgetByName(_widget,{"Panel_Input", "Panel_MsgOut", "Panel_Clipping","Text_Msg"})
    Text_Msg:setVisible(false)

    local fWidth =_Panel_Clipping:getContentSize().width
    local fHeight = _Panel_Clipping:getContentSize().height

    local clipper = _Panel_Clipping:getChildByName("_ClippingNode")
    if not clipper then

        clipper = cc.ClippingNode:create()
        clipper:setContentSize(fWidth, fHeight)
        clipper:setAnchorPoint(0,0)
        clipper:setPosition(0, 0)
        clipper:setName("_ClippingNode")
        _Panel_Clipping:addChild(clipper)

        local stencil = cc.DrawNode:create()
        local rectangle = {
            {0,0},
            {fWidth, 0},
            {fWidth, fHeight},
            {0, fHeight}
        }
        local rectangle = {cc.p(0,0), cc.p(fWidth, 0), cc.p(fWidth, fHeight), cc.p(0, fHeight)}
        local white = cc.c4f(1,1,1,1)
        stencil:drawPolygon(rectangle, 4, white, 1, white)
        clipper:setStencil(stencil)

    end

    _scrollText = clipper:getChildByName("_ScrollText")
    self._scrollStartX = fWidth
    if not _scrollText then
        _scrollText = Text_Msg:clone()
        local strMsg = "各位玩家請文明娛樂,遠離賭博。如發現賭博行為,封停賬號,並向公安機關舉報!"
        _scrollText:setString(strMsg)
        _scrollText:setVisible(true)
        _scrollText:ignoreContentAdaptWithSize(true)
        _scrollText:setPosition(fWidth+10, 5)
        _scrollText:setName("_ScrollText")
        clipper:addChild(_scrollText)

        self._scrollScheduleId = ToolUtils:schedule(handler(self, self.StartScrollUpdate), 0.0, false)
    end
end

--滾動字幕
function InputLayer:StartScrollUpdate()
    local width = _scrollText:getContentSize().width
    local posx = _scrollText:getPositionX()
    if posx < -width-10 then
        local cuMsg = ""
        local tmp = LobbyController:getGameScrollMsgs()
        if #tmp > 0  then    
            cuMsg = tmp[1]
            table.remove(tmp, 1)
        else
            _scrollText:getParent():getParent():getParent():setVisible(false)
            return
        end

        _scrollText:setString(cuMsg)
        width = _scrollText:getContentSize().width
        _scrollText:setPositionX(self._scrollStartX+10)
        _scrollText:getParent():getParent():getParent():setVisible(true)
    else
        _scrollText:setPositionX(posx - 3)
    end
end