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


你可能感兴趣的:(cocos2d-x)