绝对(很好)
首先,我们需要了解ARKit。
-
ARKit 对象不在actual
空间并基于相机所看到的内容。
-
相机并不完美;你会注意到“静止”由于照明、周围环境等原因而移动的物体。
-
没有人的手是稳的;不仅物体会移动,手机也会进行细微的调整。
现在,有了这些信息,我们就可以使用已知的变量来计算 3 个已知位置之间的角度(当然是在 3D 空间中!)。
Using 这个答案 https://stackoverflow.com/questions/19729831/angle-between-3-points-in-3d-space,我们可以看到,通过大量的数学计算,我们可以从 3 个 3D 点得出一个角度
现在,进入它的代码。
让我们得到我们的变量
- 你可以获得你的
phone
使用以下函数提供的位置SCNSceneRendererDelegate
func renderer(_ renderer: SCNSceneRenderer, willRenderScene scene: SCNScene, atTime time: TimeInterval) {
guard let pointOfView = sceneView.pointOfView else { return }
let transform = pointOfView.transform
let orientation = SCNVector3(-transform.m31, -transform.m32, transform.m33)
let location = SCNVector3(transform.m41, transform.m42, transform.m43)
let currentPositionOfCamera = orientation + location
print(currentPositionOfCamera)
}
func +(lhv:SCNVector3, rhv:SCNVector3) -> SCNVector3 {
return SCNVector3(lhv.x + rhv.x, lhv.y + rhv.y, lhv.z + rhv.z)
}
- 你可以获得你的
object
通过做
let anObject = SCNNode()
let pos = anObject.position
- 你可以获得你的
userViewDirection
以一种稍微有创意的方式——我能想到的最好的方式就是创造一个新的SCNNode
并将其放置在您面前一定距离的地方。我们可以通过使用来做到这一点这个链接 https://stackoverflow.com/questions/42029347/position-a-scenekit-object-in-front-of-scncameras-current-orientation
func updatePositionAndOrientationOf(_ node: SCNNode, withPosition position: SCNVector3, relativeTo referenceNode: SCNNode) {
let referenceNodeTransform = matrix_float4x4(referenceNode.transform)
// Setup a translation matrix with the desired position
var translationMatrix = matrix_identity_float4x4
translationMatrix.columns.3.x = position.x
translationMatrix.columns.3.y = position.y
translationMatrix.columns.3.z = position.z
// Combine the configured translation matrix with the referenceNode's transform to get the desired position AND orientation
let updatedTransform = matrix_multiply(referenceNodeTransform, translationMatrix)
node.transform = SCNMatrix4(updatedTransform)
}
//Create a global node
let lookingNode:SCNNode = SCNNode()
//Now update node say `2` away in the Z (looking direction)
let position = SCNVector3(x: 0, y: 0, z: -2)
updatePositionAndOrientationOf(lookingNode, withPosition: position, relativeTo: cameraNode)
现在我们有了 3 个变量。
我们可以简单地对它们进行数学计算:)
//Vertex is pos1
func calculateAngleBetween3Positions(pos1:SCNVector3, pos2:SCNVector3, pos3:SCNVector3) -> Float {
let v1 = SCNVector3(x: pos2.x-pos1.x, y: pos2.y-pos1.y, z: pos2.z-pos1.z)
let v2 = SCNVector3(x: pos3.x-pos1.x, y: pos3.y-pos1.y, z: pos3.z-pos1.z)
let v1Magnitude = sqrt(v1.x * v1.x + v1.y * v1.y + v1.z * v1.z)
let v1Normal = SCNVector3(x: v1.x/v1Magnitude, y: v1.y/v1Magnitude, v1.z/v1Magnitude)
let v2Magnitude = sqrt(v2.x * v2.x + v2.y * v2.y + v2.z * v2.z)
let v2Normal = SCNVector3(x: v2.x/v2Magnitude, y: v2.y/v2Magnitude, v2.z/v2Magnitude)
let result = v1Normal.x * v2Normal.x + v1Normal.y * v2Normal.y + v1Normal.z * v2Normal.z
let angle = acos(result)
return angle
}