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
Prepare a 3D model in usdz format This time, I downloaded toy drummer from Apple official website.
Create a Game project from Xcode project creation
Drag and drop the usdz file into your project
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.
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`.
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.
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()
}
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.
We provide information on iOS application development. Please follow us on Twitter as well. https://twitter.com/jugemjugemjugem