Swift ARKit+SpriteKit简易AR游戏实现

ARKit 的空间感 + SpriteKit 的 2D 趣味,Swift 里能玩的组合还挺多的。这篇文章就带你做个小实验,教你怎么用这两个框架撸一个 AR 游戏,算是上手练习也不错。写得比较清楚,步骤拆得细,代码也贴心配好了,照着来基本没啥坑。

ARKit负责搞定现实世界的部分,比如识别水平面、追踪手机位置。SpriteKit则负责 2D 游戏逻辑,比如精灵动画、触控交互啥的。两边配合好,游戏元素就能贴在真实环境里动起来,看起来还挺酷。

流程也不复杂,像是:先配置ARSession,用ARWorldTrackingConfiguration启用平面检测;再把SKScene塞进ARScene里;根据ARAnchor动态放 Sprite 节点。整体思路就是:现实世界定位,虚拟世界响应。

例如下面这个代码段,初始化配置:

let configuration = ARWorldTrackingConfiguration()
configuration.planeDetection = .horizontal
sceneView.session.run(configuration)

Sprite 场景加载也就几行:

let skView = sceneView as! SKView
let gameScene = GameScene(size: sceneView.bounds.size)
skView.presentScene(gameScene)

玩法方面,用touchesBegangesture recognizer来监听点击,做点交互效果,比如打掉怪兽、拖动角色等,体验还蛮有意思。

要注意性能问题,AR 比较吃资源。帧率别太高,Sprite 节点数量控制一下,别堆太多动画,不然手机一会儿就发烫。

如果你是想入门 ARKit 或者 SpriteKit,跟着这篇练练手挺合适。文末我还整理了几个延伸阅读,有时间可以翻翻,对理解框架会更有:

如果你正好想用 Swift 做点新奇的小项目,不如试试这个组合,AR+2D 也能玩出不少花样。

zip
swift-ARKit和SpriteKit实现的简单AR游戏.zip 预估大小:33个文件
folder
ARKitGameSpriteKit-master 文件夹
file
LICENSE 1KB
folder
ARSpriteKit.xcodeproj 文件夹
folder
project.xcworkspace 文件夹
file
contents.xcworkspacedata 156B
file
project.pbxproj 13KB
file
.gitignore 1KB
file
README.md 939B
folder
ARSpriteKit 文件夹
file
ViewController.swift 2KB
folder
Assets.xcassets 文件夹
folder
AppIcon.appiconset 文件夹
file
Contents.json 2KB
folder
ghost6.imageset 文件夹
file
Contents.json 342B
file
ghost6@3x.png 34KB
file
ghost6@2x.png 29KB
file
Contents.json 62B
folder
ghost5.imageset 文件夹
file
ghost5@3x.png 44KB
file
Contents.json 342B
file
ghost5@2x.png 34KB
folder
ghost4.imageset 文件夹
file
Contents.json 342B
file
ghost4@2x.png 31KB
file
ghost4@3x.png 37KB
folder
ghost1.imageset 文件夹
file
Contents.json 342B
file
ghost1@2x.png 24KB
file
ghost1@3x.png 31KB
folder
ghost3.imageset 文件夹
file
ghost3@2x.png 42KB
file
ghost3@3x.png 48KB
file
Contents.json 342B
folder
ghost2.imageset 文件夹
file
Contents.json 342B
file
ghost2@2x.png 27KB
file
ghost2@3x.png 36KB
file
Scene.swift 4KB
folder
Base.lproj 文件夹
file
LaunchScreen.storyboard 2KB
file
Main.storyboard 1KB
file
Scene.sks 4KB
file
AppDelegate.swift 2KB
file
ghost.wav 842KB
file
Info.plist 2KB
zip 文件大小:1.16MB