gpt4 book ai didi

swift - 如何在 SceneKit 中的两点之间画一条线?

转载 作者:行者123 更新时间:2023-11-28 05:36:31 28 4
gpt4 key购买 nike

如果我在 SceneKit 中有两个点(例如 (1,2,3)(-1,-1,-1))。如何在两者之间划清界线?

我看到有一个我可以使用的 SCNBox 对象,但它只允许我指定中心(例如通过 simdPosition)。修改它的其他方法是变换(我不知道如何使用)或欧拉角(我不确定如何计算我需要使用哪些)。

最佳答案

You can draw a line between two points using the following approach:

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])
}
}

...然后将其提供给 ViewController 中的 addLine 函数:

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)
}
}

As we all know line's width can't be changed (cause there's no property to do it), so you can use cylinder primitive geometry instead of a line:

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:

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)
}
}

关于swift - 如何在 SceneKit 中的两点之间画一条线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58470229/

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