问题描述
我有一个应用程序,旨在记录相机当前的 X、Y、Z 坐标并将它们打印出来.它使用下面的代码正确地做到了这一点
I have an app that that aims to record the camera's current X,Y,Z coordinates and print them out. It does this properly with the code down below
func renderer(_ renderer: SCNSceneRenderer, willRenderScene scene: SCNScene, atTime time: TimeInterval) {
guard let pointOfView = sceneView.pointOfView else { return }
let transform = pointOfView.transform
let CamPosition = SCNVector3(transform.m41, transform.m42, transform.m43)
print(CamPosition)
我想截断打印的输出,因为它很长.我发现这个扩展可以截断值.
I want to truncate the printed output since it's very long. I found this extension to truncate the values.
extension Double {
func truncate(places : Int)-> Double {
return Double(floor(pow(10.0, Double(places)) * self)/pow(10.0, Double(places)))
}
}
如果我打印这样的东西,这会起作用:
This works if I print something like this:
x = 1.123456789
print(x.truncate(places: 2))
但如果我像这样打印出来将无法工作:
but will not work if I print it out like this:
print(camRotation.truncate(palces:2))
它给我的错误是'SCNVector4'类型的值没有成员'truncate'"
The error it gives me says "Value of type 'SCNVector4' has no member 'truncate'"
这是我的格式问题还是 SCNVectors 不允许您使用扩展?
is this a formatting issue on my end or do SCNVectors just not allow you to use extensions?
推荐答案
camRotation
是一个 SCNVector4
.
您的扩展程序位于 Double
,而不是 SCNVector4
.
Your extension is on Double
, not SCNVector4
.
/// Double, not SCNVector4
extension Double {
func truncate(places : Int)-> Double {
return Double(floor(pow(10.0, Double(places)) * self)/pow(10.0, Double(places)))
}
}
扩展适用于任何类型,但 camRotation.truncate(palces:2)
不起作用,因为类型不匹配.
Extensions work on any type, but camRotation.truncate(palces:2)
doesn't work, because the type doesn't match.
好的,现在进入实际答案.目前,您的代码说
Ok, now on to the actual answer. Currently, your code says
let CamPosition = SCNVector3(transform.m41, transform.m42, transform.m43)
只需将 truncate
应用到每个组件:
Just apply truncate
to each of the components:
let CamPosition = SCNVector3(
transform.m41.truncate(places: 2),
transform.m42.truncate(places: 2),
transform.m43.truncate(places: 2)
)
print(CamPosition)
因为这些组件接受 Float
值,您还应该将扩展名更改为:
Because these components take in Float
values, you should also change your extension to this:
extension Float {
func truncate(places: Int) -> Float {
return Float(floor(pow(10.0, Float(places)) * self)/pow(10.0, Float(places)))
}
}
这篇关于ARKit SCNVector3 和扩展不能一起工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!