LoginSignup
4
2
お題は不問!Qiita Engineer Festa 2023で記事投稿!

【iOS】USDZ形式の3DモデルをAR空間でアニメーションさせる方法

Last updated at Posted at 2023-06-24

はじめに

USDZ形式の3DモデルをAR空間でアニメーションさせる方法を紹介します。

作るもの

USDZ形式の3DモデルをAR空間でアニメーションさせます。

デモ

準備

USDZ形式の3Dモデルを用意します。今回は、Appleの公式サイトからダウンロードできるToy Drummerを使います。
ダウンロードした3Dモデルは、Xcodeのプロジェクトに追加します。

やり方

コード全体

import SwiftUI
import RealityKit

struct ContentView: View {
    var body: some View {
        ARViewContainer()
            .edgesIgnoringSafeArea(.all)
    }
}

struct ARViewContainer: UIViewRepresentable {
    func makeUIView(context: Context) -> ARView {
        let arView = ARView(frame: .zero)
        let filename = "toy_drummer_idle"
        let modelUrl = Bundle.main.url(forResource: filename, withExtension: "usdz")!
        let anchor = AnchorEntity(world: [0, 0, 0])

        arView.scene.addAnchor(anchor)

        if let modelEntity = try? ModelEntity.load(contentsOf: modelUrl) {
            modelEntity.scale = SIMD3<Float>(0.01, 0.01, 0.01)
            modelEntity.availableAnimations.forEach {
                modelEntity.playAnimation($0.repeat())
            }

            anchor.addChild(modelEntity)
        }

        return arView
    }

    func updateUIView(_ uiView: ARView, context: Context) {}
}

解説

3Dモデルを読み込む

let filename = "toy_drummer_idle"
let modelUrl = Bundle.main.url(forResource: filename, withExtension: "usdz")!
// ...
if let modelEntity = try? ModelEntity.load(contentsOf: modelUrl) {
    // ...
}

まず、3Dモデルを読み込みます。ModelEntity.load(contentsOf:)を使うと、3Dモデルを読み込むことができます。読み込んだ3Dモデルは、ModelEntity型のオブジェクトとして扱うことができます。

3Dモデルの大きさを調整する

modelEntity.scale = SIMD3<Float>(0.01, 0.01, 0.01)

3Dモデルの大きさを調整するには、scaleプロパティを使います。scaleプロパティは、SIMD3型のオブジェクトを持っています。SIMD3型のオブジェクトは、3Dモデルの大きさを表しています。SIMD3型のオブジェクトの各要素は、x, y, zの順に、3Dモデルの大きさを表しています。今回は、3Dモデルの大きさを0.01倍にしています。

3Dモデルをアニメーションさせる

modelEntity.availableAnimations.forEach {
    modelEntity.playAnimation($0.repeat())
}

ModelEntity型のオブジェクトは、availableAnimationsプロパティを持っています。availableAnimationsプロパティには、3Dモデルに含まれるアニメーションの一覧が格納されています。availableAnimationsプロパティの中身をforEachで回し、playAnimation(_:)を使ってアニメーションを再生します。

3DモデルをAR空間に配置する

let anchor = AnchorEntity(world: [0, 0, 0])
arView.scene.addAnchor(anchor)
// ...
anchor.addChild(modelEntity)

AR空間に3Dモデルを配置するには、AnchorEntity型のオブジェクトを作成し、addChild(_:)を使って3Dモデルを追加します。

おわりに

AR空間で3Dモデルをアニメーションさせる方法を紹介しました。AR空間で3Dモデルをアニメーションさせることで、より臨場感のあるAR表現を実現できます。

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2