做了一个有关iOS AR的demo,功能就是找出周围的红包然后点击消失,这么一个简单的功能。
注:demo借鉴的泊学上的
- 项目创建成功之后进入到ViewController.swift里面。里面不需要改什么只需要在ARSKViewDelegate里面返回自己需要的Node对象就行了。
func view(_ view: ARSKView, nodeFor anchor: ARAnchor) -> SKNode? {
return SKSpriteNode(imageNamed: "money.png")
}
- 有关AR逻辑和交互的处理是放在scene.swift里面的。所以剩下的代码写在scene.swift里面就行了。
let labelTitleNode = SKLabelNode()
var createNodeCount = 0
var currentNodeCount = 0{
didSet{
labelTitleNode.text = "\(currentNodeCount) in your room"
}
}
var myTimer:Timer?
override func didMove(to view: SKView) {
labelTitleNode.fontSize = 25
labelTitleNode.color = .white
labelTitleNode.position = CGPoint(x: 0, y: view.frame.midY - 50)
addChild(labelTitleNode)
currentNodeCount = 0
myTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { timer in
self.createNode()
})
}
- 创建node
func createNode(){
if currentNodeCount == 10{
myTimer?.invalidate()
myTimer = nil
return
}
currentNodeCount += 1
createNodeCount += 1
guard let sceneView = self.view as? ARSKView else { return }
let randNumber = GKRandomSource.sharedRandom()
let xRotation = simd_float4x4(SCNMatrix4MakeRotation(randNumber.nextUniform() * Float.pi * 2, 1, 0, 0))
let yRotation = simd_float4x4(SCNMatrix4MakeRotation(randNumber.nextUniform() * Float.pi * 2, 0, 1, 0))
let rotation = simd_mul(xRotation, yRotation)
var translation = matrix_identity_float4x4
translation.columns.3.z = -1
let transform = simd_mul(rotation, translation)
let anchor = ARAnchor(transform: transform)
sceneView.session.add(anchor: anchor)
}
- 处理node交互
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let location = touch.location(in: self)
let currentNodes = nodes(at: location)
if let node = currentNodes.first{
currentNodeCount -= 1
let scaleOut = SKAction.scale(by: 2, duration: 0.2)
let fadeOut = SKAction.fadeOut(withDuration: 0.2)
let group = SKAction.group([scaleOut, fadeOut])
let sequence = SKAction.sequence([group, SKAction.removeFromParent()])
node.run(sequence)
if currentNodeCount == 0, createNodeCount == 10{
labelTitleNode.removeFromParent()
self.addChild(SKSpriteNode(imageNamed: "game_over"))
}
}
}