【Cocos2dx 3.x Lua】CCParallaxNode使用

我们知道,当我们移动时,我们会看到离我们越近的物体,会移动的越快,越远的物体,比如远处的山会移动的很慢,而最远处的物体,比如太阳几乎不动,这个现象叫视差,而在游戏中模仿视差,可以让玩家感觉到游戏中的角色的确是在移动。CCParallaxNode可以很容易的建立一个视差层,你可以控制每一层的视差率、位置和层级的高低。
 
 

Link: http://codepad.org/Wj0lMgvJ    [ raw code | fork ]  
local mapRes={
    near=string.format("%s.%s",Resource_1.map.near.loc,Resource_1.map.near.rtype),
    middle=string.format("%s.%s",Resource_1.map.middle.loc,Resource_1.map.near.rtype),
    far=string.format("%s.%s",Resource_1.map.far.loc,Resource_1.map.near.rtype)
}

local MapParallaxNode=class("MapParallaxNode",function()
    return  cc.ParallaxNode:create()
end)

MapParallaxNode.ctor=function(self)
    local s=cc.Director:getInstance():getVisibleSize()
    self._nearBg=nil
    self._middleBg=nil
    self._farBg=nil
    self._layerNode=nil
    
    self:initFarBg()
    self:initMiddleBg()
    self:initNearBg()
    
    self:setPosition(0,0)
    self:setAnchorPoint(cc.p(0,0))
    self:addChild(self._farBg, -1, cc.p(0.03,0), cc.p(0,s.height+20))
    self:addChild(self._middleBg, 1, cc.p(0.18,0), cc.p(5,s.height*2/3+90) )
    self:addChild(self._nearBg, 2, cc.p(0.65,0), cc.p(0,s.height*2/3+40))
end


--初始化地图近景
MapParallaxNode.initNearBg=function(self)
    local cache=cc.Director:getInstance():getTextureCache()
    local texture=cache:getTextureForKey(mapRes.near)
    local sprite=cc.Sprite:createWithTexture(texture)
    sprite:setPositionX(0)
    sprite:setScale(0.43)
    sprite:setAnchorPoint(cc.p(0,1))
    self._nearBg=sprite
end

--初始化地图中景
MapParallaxNode.initMiddleBg=function(self)
    local cache=cc.Director:getInstance():getTextureCache()
    local texture=cache:getTextureForKey(mapRes.middle)
    local sprite=cc.Sprite:createWithTexture(texture)
    sprite:setScale(0.7)
    sprite:setAnchorPoint(cc.p(0,1))
    self._middleBg=sprite
end

--初始化地图远景
MapParallaxNode.initFarBg=function(self)
    local cache=cc.Director:getInstance():getTextureCache()
    local texture=cache:getTextureForKey(mapRes.far)
    local sprite=cc.Sprite:createWithTexture(texture)
    sprite:setScale(0.4)
    sprite:setAnchorPoint(cc.p(0,1))
    self._farBg=sprite
end

MapParallaxNode.create=function(self)
    return MapParallaxNode.new()
end

return MapParallaxNode

 

 
CCParallaxNode添加视差精灵的函数:
    
 
 self:addChild(self._farBg, -1, cc.p(0.03,0), cc.p(0,s.height+20)) self:addChild(self._middleBg, 1, cc.p(0.18,0), cc.p(5,s.height*2/3+90) ) self:addChild(self._nearBg, 2, cc.p(0.65,0), cc.p(0,s.height*2/3+40)) 
parallaxRatio是设置不同层的x,y移动速度
 


posted @ 2015-03-15 11:58  罗松超  阅读(634)  评论(0编辑  收藏  举报