gpt4 book ai didi

swift - 两点之间的 SceneKit 对象

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

给定 2 个 3D 点(ab)和一个 SCNCapsule、SCNTorus、SCNTube 等,如何定位对象,使对象从点a 到点b

Swift 或 Objective-C 中的代码示例将不胜感激。

根据 Moustachs 的回答,我设法做了一个二维解决方案:

var v1 = SCNVector3(x: Float(a.x), y: Float(a.y), z: 0.0)
var v2 = SCNVector3(x: Float(b.x), y: Float(b.y), z: 0.0)

let height = CGFloat(v1.distance(v2))
var capsule = SCNCapsule(capRadius: 0.1, height: height)

var node = SCNNode(geometry: capsule)

var midpoint = (v1 + v2) / 2.0

node.position = midpoint

var rotp = v2 - midpoint

let rotx = atan2( rotp.y, rotp.x )
node.eulerAngles = SCNVector3Make(0.0, 0.0, rotx)

self.addChildNode(node)

我知道,完整的 3D 旋转有无限多种解决方案,但我不关心第三轴。尽管如此,似乎即使是第二轴旋转也不适合我。也许我的数学让我望而却步。谁能告诉我如何将此代码提升到 3D 空间?

(我正在使用 Swift 和 Kim Pedersens SCNVector3Extensions:https://github.com/devindazzle/SCNVector3Extensions)

最佳答案

我有好消息要告诉你!您可以链接两个点并将 SCNNode 放在这个 Vector 上!

拿着它,享受在两点之间画线的乐趣吧!

class   CylinderLine: SCNNode
{
init( parent: SCNNode,//Needed to line to your scene
v1: SCNVector3,//Source
v2: SCNVector3,//Destination
radius: CGFloat,// Radius of the cylinder
radSegmentCount: Int, // Number of faces of the cylinder
color: UIColor )// Color of the cylinder
{
super.init()

//Calcul the height of our line
let height = v1.distance(v2)

//set position to v1 coordonate
position = v1

//Create the second node to draw direction vector
let nodeV2 = SCNNode()

//define his position
nodeV2.position = v2
//add it to parent
parent.addChildNode(nodeV2)

//Align Z axis
let zAlign = SCNNode()
zAlign.eulerAngles.x = CGFloat(M_PI_2)

//create our cylinder
let cyl = SCNCylinder(radius: radius, height: CGFloat(height))
cyl.radialSegmentCount = radSegmentCount
cyl.firstMaterial?.diffuse.contents = color

//Create node with cylinder
let nodeCyl = SCNNode(geometry: cyl )
nodeCyl.position.y = CGFloat(-height/2)
zAlign.addChildNode(nodeCyl)

//Add it to child
addChildNode(zAlign)

//set constraint direction to our vector
constraints = [SCNLookAtConstraint(target: nodeV2)]
}

override init() {
super.init()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}

private extension SCNVector3{
func distance(receiver:SCNVector3) -> Float{
let xd = receiver.x - self.x
let yd = receiver.y - self.y
let zd = receiver.z - self.z
let distance = Float(sqrt(xd * xd + yd * yd + zd * zd))

if (distance < 0){
return (distance * -1)
} else {
return (distance)
}
}
}

关于swift - 两点之间的 SceneKit 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30190171/

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