gpt4 book ai didi

ios - ARKit - 从相机到 anchor 的距离

转载 作者:搜寻专家 更新时间:2023-11-01 05:55:04 25 4
gpt4 key购买 nike

我正在创建一个 anchor 并将其添加到我的 ARSKView 中,像这样在摄像机前一定距离处:

func displayToken(distance: Float) {
print("token dropped at: \(distance)")
guard let sceneView = self.view as? ARSKView else {
return
}

// Create anchor using the camera's current position
if let currentFrame = sceneView.session.currentFrame {
// Create a transform with a translation of x meters in front of the camera
var translation = matrix_identity_float4x4
translation.columns.3.z = -distance
let transform = simd_mul(currentFrame.camera.transform, translation)

// Add a new anchor to the session
let anchor = ARAnchor(transform: transform)
sceneView.session.add(anchor: anchor)
}
}

然后像这样为 anchor 创建节点:

func view(_ view: ARSKView, nodeFor anchor: ARAnchor) -> SKNode? {
// Create and configure a node for the anchor added to the view's session.
if let image = tokenImage {
let texture = SKTexture(image: image)
let tokenImageNode = SKSpriteNode(texture: texture)
tokenImageNode.name = "token"
return tokenImageNode
} else {
return nil
}
}

效果很好,我看到图像以适当的距离添加。但是,我要做的是计算 anchor /节点在您移动时在相机前面的距离。问题是使用 fabs(cameraZ - anchor.transform.columns.3.z) 似乎立即关闭了计算。请看我下面的代码,它在 update() 方法中计算相机和物体之间的距离:

override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
guard let sceneView = self.view as? ARSKView else {
return
}

if let currentFrame = sceneView.session.currentFrame {
let cameraZ = currentFrame.camera.transform.columns.3.z
for anchor in currentFrame.anchors {
if let spriteNode = sceneView.node(for: anchor), spriteNode.name == "token", intersects(spriteNode) {
// token is within the camera view
//print("token is within camera view from update method")
print("DISTANCE BETWEEN CAMERA AND TOKEN: \(fabs(cameraZ - anchor.transform.columns.3.z))")
print(cameraZ)
print(anchor.transform.columns.3.z)
}
}
}
}

感谢任何帮助以准确获得相机和 anchor 之间的距离。

最佳答案

4x4 变换矩阵的最后一列是平移向量(或相对于父坐标空间的位置),因此您只需减去这些向量即可获得两个变换之间的三维距离。

let anchorPosition = anchor.transforms.columns.3
let cameraPosition = camera.transform.columns.3

// here’s a line connecting the two points, which might be useful for other things
let cameraToAnchor = cameraPosition - anchorPosition
// and here’s just the scalar distance
let distance = length(cameraToAnchor)

您正在做的事情不正确,因为您要减去每个向量的 z 坐标。如果两个点的 x、y 和 z 不同,则仅减去 z 并不能得到距离。

关于ios - ARKit - 从相机到 anchor 的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50937214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com