0
0

XcodeでARkitを使って3DオブジェクトをAR空間に配置する

Posted at

やりたい事

Xcodeで開発したARkitを実機ビルドし、実機でAR空間に3Dオブジェクトを配置する
とりあえず初歩的な内容でデフォルトコードを公開。少し中身をいじって遊んでみる
(初期で配置されるオブジェクトを球体に変更)

環境

デバイス 環境 備考
Mac Ver 13.6.1 macos Ventura
Xcode 15.0.1 公式からダウンロード
ios 16.6

Xcode立ち上げてプロジェクト作成する

1:Create New Projectでプロジェクト作成

image.png

2:Augmented Reality Appを選択しNextで作成

image.png

3:それぞれ適正なものを選択し、名称設定してNext(Teamはあとで作成でも可)

image.png

4: 以下プロジェクトが自動生成されます
image.png

簡単にコード説明

フレームワークのインポート

import SwiftUI
import RealityKit

必要なフレームワークをインポートしている

SwiftUI:見た目を製作する際に使用
RealityKit:ARの為に開発された3Dレンダリングフレームワーク

画面へ表示する

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

AR空間に表示する:ビューを作成

    func makeUIView(context: Context) -> ARView {
        
        let arView = ARView(frame: .zero)

        // Create a cube model
        let mesh = MeshResource.generateBox(size: 0.1, cornerRadius: 0.005)
        let material = SimpleMaterial(color: .gray, roughness: 0.15, isMetallic: true)
        let model = ModelEntity(mesh: mesh, materials: [material])

        // Create horizontal plane anchor for the content
        let anchor = AnchorEntity(.plane(.horizontal, classification: .any, minimumBounds: SIMD2<Float>(0.2, 0.2)))
        anchor.children.append(model)

        // Add the horizontal plane anchor to the scene
        arView.scene.anchors.append(anchor)

        return arView
        
    }
//形状定義。generateBoxをgenerateSphereに変更すると球体オブジェクトに変更できる
let mesh = MeshResource.generateBox(size: 0.1, cornerRadius: 0.005)
//材料定義。引数で色や粗さを定義
let material = SimpleMaterial(color: .gray, roughness: 0.15, isMetallic: true)
//modelentityを作成。引数に形状と材料を渡す
let model = ModelEntity(mesh: mesh, materials: [material])
//AR空間場のどの位置にanchorを置くか。第一引数で方向。第二引数で検出するもの。第三引数でそのものの大きさ
let anchor = AnchorEntity(.plane(.horizontal, classification: .any, minimumBounds: SIMD2<Float>(0.2, 0.2)))
//modelentityを子要素に追加
anchor.children.append(model)
//AnchorEntityをシーンに追加して3dモデルをレンダリング
arView.scene.anchors.append(anchor)

entityの考え方について

Apple公式リファレンス
image.png

https://developer.apple.com/documentation/realitykit/entity

個人的な理解を纏める

  • RealityKitの表示シーンを構成する要素
  • 複数のentityがあり、木構造になっている。
  • entityの動作や表示内容はentityに設定されるコンポーネントで決定される
    transformコンポーネントや同期コンポーネントがある
0
0
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
0
0