Swift / SceneKit - 更改自定义SCNGeometry的数据透视表

时间:2018-01-12 14:25:25

标签: ios swift scenekit

我在this question的帮助下创建了一个自定义SCNGeometry对象。但是,将几何应用于SCNNode时,枢轴似乎不在正确的位置。旋转节点时,我想围绕几何体的中心旋转节点,而是围绕另一个点旋转。我可以通过使用node.pivot = SCNMatrix4MakeTranslation(ARROW_WIDTH / 2, 0, ARROW_LENGTH / 2)更改节点的轴来解决此问题,其中ARROW_WIDTH指的是几何的宽度,ARROW_LENGTH指的是几何的长度。然而,这并不理想,因为每次使用几何体创建新节点时,我都必须手动修复节点的轴。有没有办法定义" pivot"某种程度的几何形状?

创建自定义SCNGeometry的当前代码:

/**
 Default constructor of an arrow geometry. This constructor takes in the needed parameters to construct the geometry at the specified size.
 - parameters:
    - length: The length of the arrow, which is the dimension that the arrow is pointing in.
    - height: The height of the arrow, which is the thickness of the arrow.
    - width: The width of the arrow, which defines the width of the arrow.
    - indent: The indent of the arrow, which is the point and gap on the front and back of the arrow.
 */
init(length: Float, height: Float, width: Float, indent: Float) {
    self.length = length
    self.height = height
    self.width = width
    self.indent = indent > length ? length : indent

    // Vertices
    let v0 = SCNVector3(0, height / 2, 0)
    let v1 = SCNVector3(width / 2, height / 2, indent)
    ... more vertices
    let h4 = SCNVector3(width, -height / 2, indent)
    let h5 = SCNVector3(width / 2, -height / 2, length - indent)

    let vertices = [
        // Top layer bottom triangles
        v0, v1, h0,
        v1, v2, h1,
        ... more vertices
        v4, v10, v5,
        v10, v11, v5
    ]

    // Normals
    let pX = SCNVector3(1, 0, 0)
    ... more normals
    let topRight = calculateNormal(v1: v3, v2: v9, v3: v4)

    let normals = [
        // Top layer bottom triangles
        pY, pY, pY,
        ... more normals
        topLeft, topLeft, topLeft
    ]

    // Indices
    let indices: [Int32] = vertices.enumerated().map({ Int32($0.0) })

    // Sources
    let vertexSource = SCNGeometrySource(vertices: vertices)
    let normalSource = SCNGeometrySource(vertices: normals)

    // Create the geometry
    let pointer = UnsafeRawPointer(indices)
    let indexData = NSData(bytes: pointer, length: MemoryLayout<Int32>.size * indices.count)

    let element = SCNGeometryElement(data: indexData as Data, primitiveType: .triangles, primitiveCount: indices.count / 3, bytesPerIndex: MemoryLayout<Int32>.size)

    self._geometry = SCNGeometry(sources: [vertexSource, normalSource], elements: [element])
}

如果不在节点上应用手动枢轴修复,箭头会像这样渲染:(注意红点是场景原点(0,0,0),箭头位于场景的根节点处相同的位置) no manual pivot fix

在节点上应用手动pivot fix时,箭头呈现如下: manual pivot fix

0 个答案:

没有答案