SceneKit - 骨骼动画

1.import SceneKit 导入框架

2.在视图上添加 scnView 用以展示模式

    lazy var scnView: SCNView = {
        let scnView = SCNView(frame: self.view.bounds)
        scnView.scene = SCNScene()
        scnView.backgroundColor = .red
        scnView.allowsCameraControl = true
        return scnView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(scnView)
        playSomePart()
    }

3.加载 dae 文件
.dae 文件中带有动画 将会直接播放动画
.xcode9中资源文件需要通过 右键 addfile 的方法导入否则资源文件不会被打包到项目中

        if let resourceUrl = Bundle.main.url(forResource: "skinning", withExtension: "dae") {
            if FileManager.default.fileExists(atPath: resourceUrl.path) {
                let sceneSource = SCNSceneSource(url: resourceUrl, options: nil)
                scnView.scene = sceneSource?.scene(options: nil)
            }
        }

4.播放部分动画

    func playSomePart() {
        if let resourceUrl = Bundle.main.url(forResource: "skinning", withExtension: "dae") {
            if FileManager.default.fileExists(atPath: resourceUrl.path) {
                let sceneSource = SCNSceneSource(url: resourceUrl, options: nil)
                scnView.scene = sceneSource?.scene(options: nil)
                
                //获得sceneSource 中所有动画类的 identifier
                let parts = sceneSource?.identifiersOfEntries(withClass: CAAnimation.self)
                let partsCount = parts?.count ?? 0
                var animtionArrM = NSMutableArray(capacity: partsCount) as! [CAAnimation]
                var maxDuration:CFTimeInterval = 0
                
                //通过 identifiers 获得 每个动画animation 添加到数组中备用
                for index in 0..

5.显示骨骼

//显示骨骼
let boneNode = scnView.scene?.rootNode.childNode(withName: "skeleton", recursively: true)   
self.visualizeBones(show: true, node: boneNode!, scale: 1)
    func visualizeBones(show:Bool,node:SCNNode,scale:CFloat) {
        
        let scaleX = node.scale.x * scale;
        print("scale\(scaleX)")
        if (show) {
            if (node.geometry == nil) {
                node.geometry = SCNBox(width: CGFloat(6/scaleX), height: CGFloat(6/scaleX), length: CGFloat(6/scaleX), chamferRadius: 0.5)
            }else {
                let boxNode = node.geometry?.isKind(of: SCNBox.self)
                if(boxNode == true){
                    node.geometry = nil
                }
            }
        }
        for child:SCNNode in node.childNodes {
            self.visualizeBones(show: show, node: child, scale: scaleX)
        }
    }
}

你可能感兴趣的:(SceneKit - 骨骼动画)