[SWIFT] Load a 3D model in usdz format into SceneKit and animate it

I will show you how to load a 3D model in usdz format into SceneKit and animate it.

I referred to this article, but now I don't need to use ModelIO, so I'll write it again. Load 3D model in USDZ format with Model I / O and use it with SceneKit

procedure

  1. Prepare a 3D model in usdz format This time, I downloaded toy drummer from Apple official website.

  2. Create a Game project from Xcode project creation

  3. Drag and drop the usdz file into your project

image.png

  1. Load the model

I will write it in viewDidLoad of GameViewController.

GameViewController.swift


override func viewDidLoad() {
    super.viewDidLoad()
    
    guard let url = Bundle.main.url(forResource: "toy_drummer", withExtension: "usdz") else { fatalError() }
    let scene = try! SCNScene(url: url, options: [.checkConsistency: true])

If you pass the url directly to SCNScene, you can load the usdz file as it is.

  1. Control the animation Actually, at this point, the animation included in usdz starts playing, and the Toy drummer starts playing the drums.

Let's stop only the movement of the left arm.

If you open the usdz file, you will see that the left arm is named ʻarm_keft and has an animation named transform`. image.png

Take it out with a code.

GameViewController.swift


let drummer = scene.rootNode.childNode(withName: "toy_drummer", recursively: true)!

let armLeft = drummer.childNode(withName: "arm_left", recursively: true)
let player = armLeft?.animationPlayer(forKey: "transform")
player?.stop()

I am getting the left arm node from the toy_drummer node. And I get the transform animation and stop it.

  1. Make the left arm move when tapped

Earlier we got the animationPlayer in a local variable, but now we want to save it in an instance variable so that it can be used in event handlers.

GameViewController.swift


class GameViewController: UIViewController {
    var player: SCNAnimationPlayer?

In the event handler, start the animation of the left arm moving. It is necessary to call ʻaddGestureRecognizer` to register the event handler, but the code that is automatically generated when the Game project is created is diverted.

GameViewController.swift


@objc
func handleTap(_ gestureRecognize: UIGestureRecognizer) {
    player?.animation.repeatCount = 1
    player?.play()
}

finish

The left arm animates when tapped. There are other animations as well, but this time you can see that they are looping because they are not controlled.

toy_drummer.gif

We provide information on iOS application development. Please follow us on Twitter as well. https://twitter.com/jugemjugemjugem

Recommended Posts

Load a 3D model in usdz format into SceneKit and animate it
Write a class in Kotlin and call it in Java
21 Load the script from a file and execute it
(Ruby on Rails6) Creating a database and displaying it in a view
I wrote a route search program in TDD and refactored it