SenceKit的学习
用SceneKit Scene File 直接可以搭建3D场景 简单便捷且容易计算
主体代码:
//
// ViewController.swift
// Planet-rotation
//
// Created by Mengduan on 2023/5/28.import UIKit
import SceneKit//mercury
//venus
//earth
//mars
//saturnvar index : Int = 1class ViewController: UIViewController {//行星表面纹理UIimage数组var plents = ["mercury","venus","earth","mars","saturn"]lazy var sceneView : SCNView = {let sceneView = SCNView(frame: self.view.frame)sceneView.allowsCameraControl = truesceneView.backgroundColor = .secondarySystemFillreturn sceneView}()lazy var scene : SCNScene = {let scene = SCNScene(named: "SceneKit Scene.scn")let sunNode = scene?.rootNode.childNode(withName: "sun", recursively: false)sunNode?.geometry?.firstMaterial?.diffuse.contents = UIImage(named: "sun")sunrotation(node: sunNode!)//光圈let sunHaloNode = SCNNode()sunHaloNode.geometry = SCNPlane(width: (sunNode?.frame.size.width)!, height: (sunNode?.frame.size.height)!)sunHaloNode.geometry?.firstMaterial?.diffuse.contents = UIImage(named: "sunhalo")sunHaloNode.geometry?.firstMaterial?.lightingModel = SCNMaterial.LightingModel.constantsunHaloNode.geometry?.firstMaterial?.writesToDepthBuffer = falsesunHaloNode.opacity = 5sunNode?.addChildNode(sunHaloNode)for plent in plents {//遍历各个行星,添加其纹理diffuse.contentlet id = plent//recursively为false时,是在当前scene中查找withname,为true时是在全局查找let node = scene?.rootNode.childNode(withName: id, recursively: true)let ui = UIImage(named: id)node?.geometry?.firstMaterial?.diffuse.contents = ui}//SceneKit 可以将这六个图像用于一种称为天空盒的常见 3D 编程技术。通过使用这些图像作为场景的背景,SceneKit 从六张图像中创建一个立方体,并将整个场景放入立方体中。//创建一个包含六个天空盒图像的数组let skyboxui = (1...6).map{UIImage(named: "skybox\($0)")}scene?.background.contents = skyboxuireturn scene!}()override func viewDidLoad() {super.viewDidLoad()// Do any additional setup after loading the view.
// self.view.backgroundColor = .cyanself.view.addSubview(sceneView)sceneView.scene = scenefor plent in plents {let id = plentlet node = scene.rootNode.childNode(withName: id, recursively: true)plentrotation(node: node!)}}}func sunrotation(node : SCNNode){let animation = CABasicAnimation(keyPath: "rotation")animation.toValue = SCNVector4Make(0, 1, 0, Float(Double.pi) * 2)animation.duration = 10.0animation.repeatCount = Float.greatestFiniteMagnitudenode.addAnimation(animation, forKey: "sun-texture")}func plentrotation(node : SCNNode){let animation = CABasicAnimation(keyPath: "rotation")animation.toValue = NSValue(scnVector4: SCNVector4(0, 1, 0, Double.pi * 2))//围绕自己的y轴转动animation.duration = CFTimeInterval(2 * index)animation.repeatCount = Float.greatestFiniteMagnitudenode.addAnimation(animation, forKey: "earth rotation around sun")
// node.runAction(SCNAction.repeatForever(SCNAction.rotateBy(x: 0, y: 2, z: Double.pi*2, duration: TimeInterval(index))), forKey: "texture")index = index + 5
}
运行结果如下:
demo:
参考:SceneKit 3D Programming for iOS: Getting Started | Kodeco
更多推荐
SenceKit的学习
发布评论