やりたい事
Xcodeで開発したARkitを実機ビルドし、実機でAR空間に3Dオブジェクトを配置する
とりあえず初歩的な内容でデフォルトコードを公開。少し中身をいじって遊んでみる
(初期で配置されるオブジェクトを球体に変更)
環境
デバイス | 環境 | 備考 |
---|---|---|
Mac | Ver 13.6.1 | macos Ventura |
Xcode | 15.0.1 | 公式からダウンロード |
ios | 16.6 |
Xcode立ち上げてプロジェクト作成する
1:Create New Projectでプロジェクト作成
2:Augmented Reality Appを選択しNextで作成
3:それぞれ適正なものを選択し、名称設定してNext(Teamはあとで作成でも可)
簡単にコード説明
フレームワークのインポート
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の考え方について
個人的な理解を纏める
- RealityKitの表示シーンを構成する要素
- 複数のentityがあり、木構造になっている。
- entityの動作や表示内容はentityに設定されるコンポーネントで決定される
transformコンポーネントや同期コンポーネントがある