本节学习目标
10FD7AC6-5600-4313-8775-0F8A12A06F19.png
如图所示
白的部分是一个plane几何的节点,我们需要将一个SCNScene渲染到这个节点上,来实现画中画效果
Scenekit_17.gif
接下来 我简单的说一下思路
1.首先我们需要一个SCNView 作为渲染的视图, 2.然后创建一个游戏场景SCNScene 给这个SCNView视图 3.给场景中添加一个地板节点和一个plane平面节点 4.我们还创建一个SCNScene 场景,将我们需要放置在plane上的3D 元素添加到这个场景中进去, 5.注意如果直接使用plane.firstMaterial?.diffuse.contents = scene 这样做是渲染不出来画面的,我们需要创建一个SCNView 来持有scene ,然后将SCNView 设置为plane渲染的内容
下面是全部代码
let scene = SCNScene()
// 创建照相机
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
cameraNode.camera?.automaticallyAdjustsZRange = true
scene.rootNode.addChildNode(cameraNode)
cameraNode.position = SCNVector3(x: 0, y: 10, z: 100)
// 创建灯光
let lightNode = SCNNode()
lightNode.light = SCNLight()
lightNode.light!.type = .omni
lightNode.position = SCNVector3(x: 0, y: 10, z: 10)
scene.rootNode.addChildNode(lightNode)
let ambientLightNode = SCNNode()
ambientLightNode.light = SCNLight()
ambientLightNode.light!.type = .ambient
ambientLightNode.light!.color = UIColor.darkGray
scene.rootNode.addChildNode(ambientLightNode)
// 设置相关属性
let scnView = self.view as! SCNView
scnView.scene = scene
scnView.allowsCameraControl = true
scnView.showsStatistics = true
scnView.backgroundColor = UIColor.black
// 创建一面墙
let plane = SCNPlane(width: 50, height: 50)
let planeNode = SCNNode(geometry: plane)
planeNode.position = SCNVector3Make(0, 25, 0)
scene.rootNode.addChildNode(planeNode)
scnView.isPlaying = true
// 创建一个地板
let floorNode = SCNNode()
floorNode.geometry = SCNFloor()
floorNode.geometry?.firstMaterial?.diffuse.contents = "floor.jpg"
scene.rootNode.addChildNode(floorNode)
// 创建内画面
let sceneShip = SCNScene(named: "art.scnassets/ship.scn")!
let cameraNode1 = SCNNode()
cameraNode1.camera = SCNCamera()
sceneShip.rootNode.addChildNode(cameraNode1)
cameraNode1.position = SCNVector3(x: 0, y: 0, z: 10)
let ship = sceneShip.rootNode.childNode(withName: "ship", recursively: true)!
ship.runAction(SCNAction.repeatForever(SCNAction.rotateBy(x: 0, y: 2, z: 0, duration: 1)))
let view = SCNView(frame: CGRect(x: 0, y: 0, width: 1000, height: 1000))
view.scene = sceneShip
view.backgroundColor = UIColor.gray
// 设置内画面视图为plane渲染的纹理
plane.firstMaterial?.diffuse.contents = view