业务需求需要在2d场景内显示3d的东西,其实原理就是用多个摄像机,在2d的scene实例化这个,然后创建贴图,则会沿Z轴朝里移动,闲话不哆嗦,直接贴代码
-- 投影摄像机
local CameraPersLayer = class("CameraLayer", function ()
local layer = cc.Layer:create()
return layer
end)
function CameraPersLayer:ctor(_cameraFlag)
self._camera = nil
self._cameraFlag = _cameraFlag
self:init()
end
function CameraPersLayer:init()
self:registerScriptHandler(function (event)
if event == "enter" then
self:onEnter()
elseif event == "exit" then
self:onExit()
end
end)
end
function CameraPersLayer:setNodeCameraMask(_node )
_node:setCameraMask(self._cameraFlag)
end
function CameraPersLayer:onEnter( )
self.m_layer = cc.Layer:create()
self:addChild(self.m_layer)
local winSize = cc.Director:getInstance():getWinSize()
local zeye = cc.Director:getInstance():getZEye();
local eye = cc.vec3(winSize.width/2, winSize.height/2, zeye)
local center = cc.vec3(winSize.width/2, winSize.height/2, 0)
local up = cc.vec3(0, 1, 0)
self._camera = cc.Camera:createPerspective(60, winSize.width / winSize.height, 10, zeye + winSize.height / 2)
self._camera:setCameraFlag(self._cameraFlag)
self._camera:setDepth(self._cameraFlag)
self.m_layer:addChild(self._camera)
self._camera:setPosition3D(eye);
self._camera:lookAt(center, up);
self:initUI( )
self:setNodeCameraMask(self.m_layer )
end
function CameraPersLayer:onExit( )
end
function CameraPersLayer:initUI( )
local spr3d = cc.Sprite3D:create()
local sp = util_createSprite("Common/ZooMania_bg_2.png")
spr3d:addChild(sp)
self.m_layer:addChild(spr3d)
spr3d:setScale(0.5)
spr3d:setPosition3D(cc.vec3(display.center.x,display.center.y,-608))
spr3d:setRotation3D(cc.vec3(0,70,-90))
local z = -608
schedule(self,function( )
z = z + 10
spr3d:setPosition3D(cc.vec3(display.center.x,display.center.y,z))
end,0.2)
end
return CameraPersLayer