问题描述
如果我在SceneKit中有两个点(例如(1,2,3)
和(-1,-1,-1)
)。我如何在两者之间画一条线?
If I have two points in SceneKit (e.g. (1,2,3)
and (-1,-1,-1)
). How do I draw a line between the two?
我看到我可以使用一个SCNBox对象,但这只允许我指定中心(例如通过 simdPosition
)。修改它的其他方法是变换(我不知道如何使用)或欧拉角(我不确定如何计算需要使用的角度)。
I see that there is a SCNBox object I may be able to use, but that only allows me to specify the center (e.g. via simdPosition
). The other ways to modify it are the transform (which I don't know how to use), or the Euler angles (which I'm not sure how to calculate which ones I need to use).
推荐答案
import SceneKit
extension SCNGeometry {
class func line(vector1: SCNVector3,
vector2: SCNVector3) -> SCNGeometry {
let sources = SCNGeometrySource(vertices: [vector1,
vector2])
let index: [Int32] = [0,1]
let elements = SCNGeometryElement(indices: index,
primitiveType: .line)
return SCNGeometry(sources: [sources],
elements: [elements])
}
}
...然后将其输入到 addLine
在ViewController中的功能:
...and then feed it to addLine
function in ViewController:
class ViewController: UIViewController {
// Some code...
func addLine(start: SCNVector3, end: SCNVector3) {
let lineGeo = SCNGeometry.line(vector1: start,
vector2: end)
let lineNode = SCNNode(geometry: lineGeo)
sceneView.scene.rootNode.addChildNode(lineNode)
}
}
extension SCNGeometry {
class func cylinderLine(from: SCNVector3,
to: SCNVector3,
segments: Int) -> SCNNode {
let x1 = from.x
let x2 = to.x
let y1 = from.y
let y2 = to.y
let z1 = from.z
let z2 = to.z
let distance = sqrtf( (x2-x1) * (x2-x1) +
(y2-y1) * (y2-y1) +
(z2-z1) * (z2-z1) )
let cylinder = SCNCylinder(radius: 0.005,
height: CGFloat(distance))
cylinder.radialSegmentCount = segments
cylinder.firstMaterial?.diffuse.contents = UIColor.green
let lineNode = SCNNode(geometry: cylinder)
lineNode.position = SCNVector3(x: (from.x + to.x) / 2,
y: (from.y + to.y) / 2,
z: (from.z + to.z) / 2)
lineNode.eulerAngles = SCNVector3(Float.pi / 2,
acos((to.z-from.z)/distance),
atan2((to.y-from.y),(to.x-from.x)))
return lineNode
}
}
...然后以相同方式喂到ViewController:
...then feed it the same way to ViewController:
class ViewController: UIViewController {
// Some code...
func addLine(start: SCNVector3, end: SCNVector3) {
let cylinderLineNode = SCNGeometry.cylinderLine(from: start,
to: end,
segments: 3)
sceneView.scene.rootNode.addChildNode(cylinderLineNode)
}
}
这篇关于如何在SceneKit中的两个点之间画一条线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!