ARKit
运行版本
iOS 11.0+
xcode 10.0+
1.新建并运行官方自带的demo
XCode : File --> New --> Project --> Augmented Reality App
查看工程,会出现一个art.scnassets 目录,这目录下的 .scn文件就是展示的3D模型,.png是模型对应的贴纸。
连接设备,直接运行就可以先看到如下
3.代码查看
- (void)viewDidLoad {
[super viewDidLoad];
// 实现 ARSCNViewDelegate 的delegate
self.sceneView.delegate = self;
// 显示控制台,默认值是NO
self.sceneView.showsStatistics = YES;
// new 一个新的模型
SCNScene *scene = [SCNScene sceneNamed:@"art.scnassets/ship.scn"];
// 显示模型
self.sceneView.scene = scene;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// 创建 session 摄像头配置
ARWorldTrackingConfiguration *configuration = [ARWorldTrackingConfiguration new];
// 运行ARSession
[self.sceneView.session runWithConfiguration:configuration];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
//停止ARSession
[self.sceneView.session pause];
}
这就是Apple提供的简单的ARKit Demo,那现在我们不需要他的demo,需要运行自己的3D模型呢。
2.加载本地3D模型文件
首先需要有3D模型文件,文件可以是.obj,.dae,.scn等等,此项文件来自此网站[3D模型文件](https://free3d.com/3d-models/characters?page=3)
一:在项目目录中通过Add File将需要显示的.obj文件添加到项目中,Stick_Figure_by_Swp.obj 文件为需要显示的模型
二:利用storyboard简单构建整个如图层级
三:代码加载3D模型
ShowObjViewController 复制加载显示模型,具体代码如下:
- (void)viewDidLoad {
[super viewDidLoad];
//获取文件url
NSURL *url = [[NSBundle mainBundle] URLForResource:@"Stick_Figure_by_Swp" withExtension:@"obj"];
// new SCNReferenceNode 是用来从场景文件中加载node
SCNReferenceNode * cunstomNode = [SCNReferenceNode referenceNodeWithURL:url];
[cunstomNode load];
//new 需要显示的元素
SCNNode *scnNode = [[SCNNode alloc] init];
[scnNode addChildNode:cunstomNode];
//设置 node的scale
[scnNode setScale: SCNVector3Make(0.05,0.05,0.05)];
//设置delegate
self.sceneView.delegate = self;
//设置显示控制台
self.sceneView.showsStatistics = YES;
// 场景添加显示节点
[self.sceneView.scene.rootNode addChildNode:scnNode];
}
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
ARWorldTrackingConfiguration *configuration = [ARWorldTrackingConfiguration new];
[self.sceneView.session runWithConfiguration:configuration];
}
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[self.sceneView.session pause];
}
四:连接设备,运行项目就可以显示加载的3D模型了。
3.obj文件转scn文件
操作步骤:
一:复制一份.obj文件,选中文件
二:XCode -- Editor -- Convert to SceneKit scene file format (.scn)
三:弹出对话框,点击Convert
四:将转换后的Stick_Figure_by_Swp_scn.scn文件,拖到到 【art.scnassets】中
五:ShowScnViewController 实现模型显示
六:连接设备,运行,显示。
具体可以查看demo GitHun地址
参考地址