我正在尝试使用ARKit制作iOS应用。到目前为止,我已经使用了#34;放置对象" Apple的例子并对其进行了扩充,因此它具有我自己的几何体。这一部分都很有效。
我有几个不同的物体可以放在地上。为了简单地解释这些物体,它们是在它们前面有门的盒子。
我遇到的问题是我现在想要向应用程序添加手势,这样当门被轻敲时它会旋转打开。然后当它再次敲击时,门就会关闭。
我已经找了一些关于如何做到但却找不到任何东西的教程。有人可以向我解释如何执行此操作或指向我的教程,了解如何实现此交互性。
谢谢! :)
答案 0 :(得分:3)
下面是一个基本的快速游乐场,可以在装载时创建一扇门。通过敲击门可以旋转打开,再次敲击将关闭门。我已将代码分解为不同的功能,以便您可以看到门是如何打开的。然后关闭。
import ARKit
import SceneKit
import PlaygroundSupport
class ViewController: NSObject {
var doorNode: SCNNode!
var doorisOpen: Bool!
var sceneView: ARSCNView
init(sceneView: ARSCNView) {
self.sceneView = sceneView
super.init()
self.setupWorldTracking()
self.sceneView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(ViewController.handleTap(_:))))
// place door
self.sceneView.scene.rootNode.addChildNode(createDoor(position: SCNVector3(0,0,-1)))
}
private func setupWorldTracking() {
if ARWorldTrackingConfiguration.isSupported {
let configuration = ARWorldTrackingConfiguration()
configuration.planeDetection = .horizontal
configuration.isLightEstimationEnabled = true
self.sceneView.session.run(configuration, options: [])
}
}
@objc func handleTap(_ gesture: UITapGestureRecognizer) {
let results = self.sceneView.hitTest(gesture.location(in: gesture.view), types: ARHitTestResult.ResultType.featurePoint)
guard let result: ARHitTestResult = results.first else {
return
}
let tappedNode = self.sceneView.hitTest(gesture.location(in: gesture.view), options: [:])
if !tappedNode.isEmpty {
let node = tappedNode[0].node
if doorisOpen == true {
// rotate door
closeDoor()
} else {
// rotate door
openDoor()
}
} else {
return
}
}
func createDoor(position: SCNVector3) -> SCNNode {
let door = SCNBox(width: 0.3, height: 0.7, length: 0.025, chamferRadius: 0)
doorNode = SCNNode(geometry: door)
door.firstMaterial?.locksAmbientWithDiffuse = true
door.firstMaterial?.diffuse.contents = UIColor.brown
// place door
doorNode.position = position
// Pivot door from the end
endPivot(for: doorNode)
return doorNode
}
func openDoor() {
let rotate = SCNAction.rotateBy(x: 0, y: CGFloat(degToRadians(degrees: 90)), z: 0, duration: 1)
doorNode.runAction(rotate)
doorisOpen = true
}
func closeDoor() {
let rotate = SCNAction.rotateBy(x: 0, y: CGFloat(degToRadians(degrees: -90)), z: 0, duration: 1)
doorNode.runAction(rotate)
doorisOpen = false
}
func endPivot(for node: SCNNode) {
var min = SCNVector3Zero
var max = SCNVector3Zero
node.__getBoundingBoxMin(&min, max: &max)
node.pivot = SCNMatrix4MakeTranslation(min.x, 0, 0)
}
func degToRadians(degrees:Double) -> Double
{
return degrees * (M_PI / 180);
}
}
let sceneView = ARSCNView()
let viewController = ViewController(sceneView: sceneView)
sceneView.autoenablesDefaultLighting = true
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = viewController.sceneView