HIT해

[iOS/SceneKit] .scn Material 을 바꿔보자 본문

Swift/Swift 개발 노트

[iOS/SceneKit] .scn Material 을 바꿔보자

힛해 2024. 8. 18. 02:08
728x90

사용자가 3D 모델의 색을 바꿀 수 있는 기능이 있으면 어떨까 생각이들어 색을 변경하는 기능을 만들어보았다.

 

모델에 접근하려면 NodeName을 알아야 접근할 수 있다.

 

ModelNodeName 출력하기

func printNodeDetails(node: SCNNode, depth: Int = 0) {
    // 현재 노드의 이름과 깊이를 출력합니다.
    let indentation = String(repeating: "  ", count: depth)
    print("\(indentation)Node name: \(node.name ?? "Unnamed")")
    
    // 노드의 지오메트리가 있으면 지오메트리의 정보를 출력합니다.
    if let geometry = node.geometry {
        print("\(indentation)  Geometry: \(geometry.name ?? "Unnamed")")
        for material in geometry.materials {
            if let color = material.diffuse.contents as? UIColor {
                print("\(indentation)    Material color: \(color)")
            }
        }
    }
    
    // 자식 노드가 있으면 자식 노드를 재귀적으로 탐색합니다.
    for childNode in node.childNodes {
        printNodeDetails(node: childNode, depth: depth + 1)
    }
}

 

return 으로 바로 값을 받아올 수 있지만 Node가 있을수도 있고 간단한 테스트이기 때문애 출력만 해본다.

 

실행결과

Node name: Unnamed
  Node name: 돌_Material.004
    Geometry: 돌_Material.004
      Material color: UIExtendedSRGBColorSpace 1 1 1 1
      Material color: UIExtendedSRGBColorSpace 1 1 1 1
      Material color: UIExtendedSRGBColorSpace 1 1 1 1
      Material color: UIExtendedSRGBColorSpace 1 1 1 1

 

돌_Material.004로 저장되어있다.

 

이부분은 블렌더 또는 유니티 상에서 모델링작업을 하며 디자이너님이 명명하신 이름이다.

 

이제 해당 NodeName에 접근해 색상을 변경해보자.

 

func loadScene() -> SCNScene {
        let scene = SCNScene(named: "Dols.scnassets/cupid.scn") ?? SCNScene()
               
      
        
        let cameraNode = SCNNode()
        cameraNode.camera = SCNCamera()
        // z값을 높일수록 멀어진다
        cameraNode.position = SCNVector3(x: 0, y: 0, z: 4)
        //SceneKit에서 카메라의 Z축 범위를 자동으로 조정하도록 설정하는 속성
//        cameraNode.camera?.automaticallyAdjustsZRange = true
        scene.rootNode.addChildNode(cameraNode)
        
        printNodeDetails(node : scene.rootNode)
        
        if let modelNode = scene.rootNode.childNode(withName: "돌_Material.004", recursively: true) {
              // 모델의 지오메트리 가져오기
              if let geometry = modelNode.geometry {
                  // 모델의 재질 가져오기
                  for material in geometry.materials {
                      // 재질의 색상 변경
                      material.diffuse.contents = UIColor.red // 원하는 색상으로 변경
                  }
              }
          }
        
        // 모델의 색상을 변경합니다.
           if let modelNode = scene.rootNode.childNode(withName: "modelNodeName", recursively: true) {
               // 모델의 지오메트리 가져오기
               if let geometry = modelNode.geometry {
                   // 모델의 재질 가져오기
                   for material in geometry.materials {
                       // 재질의 색상 변경
                       material.diffuse.contents = UIColor.red // 원하는 색상으로 변경
                   }
               }
           }
        
        return scene
    }

 

이렇게 하면 색을 변경할 수 있다~~