【问题标题】:Trouble Arranging SceneKit Nodes into a Grid将 SceneKit 节点排列到网格中时遇到问题
【发布时间】:2019-06-07 16:56:46
【问题描述】:

我正在尝试将一组节点排列成一个网格,我有三个不同大小的节点,所以我将它们从最大到最小排列在一个方形网格中。

如果所有节点的大小都相同,那效果很好

[][][]
[][][]
[][][]

当新行包含的节点小于前一个节点时,问题就出现了,然后我在行之间获得了额外的空间

[][][]
[][][]

[][][]

我确实希望在行(和列)之间有一个空间,但是我希望能够控制该空间的大小。

我快疯了。我在我的代码中看不到任何会增加这个额外空间的东西。我知道问题是因为节点大小不同,但我不知道它是如何发生的。

我认为这不是问题

我目前正在操场上运行它。

public static func grid(theseObjects: [SCNNode]) -> SCNNode {
        let nodesSortedByVolume = theseObjects.sorted(by: {$0.volume > $1.volume } )

    let finalNode = SCNNode()
    var xOffset: Float = 0.0
    var zOffset: Float = 0.0
    let gridSize = Int(Double(theseObjects.count).squareRoot().rounded())


    for (index, node) in nodesSortedByVolume.enumerated() {
        let adjustedIndex = index + 1

        node.position = SCNVector3(xOffset, 0.0, zOffset)
        finalNode.addChildNode(node)
        xOffset += node.width //(node.width + self.spacer)

        if (adjustedIndex >= gridSize) && adjustedIndex.isMultiple(of: gridSize)  {

            zOffset += node.depth
            xOffset = 0.0
        }
    }

    return finalNode
}

编辑:我添加了默认框节点,以消除我的模型存在问题的任何疑问,并且可以更轻松地查看定位数学。我添加了打印语句来显示节点的放置位置:

Placing node.name: "large box 1" at node.position.z:0.0, node.position.x:0.0 zOffset: 0.0
    node.depth is 2.0
    node.name "large box 1" is at finalNode.position.z: 0.0, finalNode.position.x: 0.0

    Placing node.name: "large box 2" at node.position.z:0.0, node.position.x:2.0 zOffset: 0.0
    node.depth is 2.0
    node.name "large box 2" is at finalNode.position.z: 0.0, finalNode.position.x: 2.0

setup new row with zOffset of 2.0

    Placing node.name: "small box 1" at node.position.z:2.0, node.position.x:0.0 zOffset: 2.0
    node.depth is 1.0
    node.name "small box 1" is at finalNode.position.z: 2.0, finalNode.position.x: 0.0

    Placing node.name: "small box 2" at node.position.z:2.0, node.position.x:1.0 zOffset: 2.0
    node.depth is 1.0
    node.name "small box 2" is at finalNode.position.z: 2.0, finalNode.position.x: 1.0

如您所见,小方框被放置在 2.0 的 z 位置,这应该没有间隙,但是当您查看下面的屏幕截图时,会有很大的间隙。

如果我添加更多大框,它们会正确网格,直到引入新尺寸:

【问题讨论】:

  • 您好,node.depth 和 node.width 是什么?扩大 ?为什么不使用节点几何的boundingBox?
  • 是的,它是一个扩展,从boundingBox中获取节点的高度、宽度和深度。
  • 你能发送更多代码吗?
  • 如果你从节点的中心定位,你不想添加节点深度,你想添加一半的前一个节点和一半的新节点。您的小节点位置应为 1.5。
  • 或者改变节点的枢轴也应该有效。 node.pivot = SCNMatrix4MakeTranslation(0, 0, -0.5 * node.depth);

标签: swift scenekit


【解决方案1】:

感谢您提供的打印值。
创建 SCNNode 时,几何图形以枢轴点为中心。因此,如果您有一个尺寸为 200 x 200 x 200 单位的几何立方体,则边界框从 (-100, -100, -100) 变为 (100, 100, 100)。

在您的循环中,当您想换线时,您可以添加 200 个单位。
事实上,您必须添加一半(100 个单位)和下一个 SNNode 的一半(50 个单位)。

这里有两张图片来解释:

实际代码的结果

您添加 200 个单位,但您只能添加第一个网格的一半高度(100 个单位)和第二个网格的一半高度(50 个单位)。

希望有帮助! 就像@James P 提到的那样,改变支点更容易......

对不起我糟糕的英语。

【讨论】:

  • 现在这完全有道理,我完全可以看出我哪里出错了。很好的解释。谢谢?
猜你喜欢
  • 1970-01-01
  • 2019-09-06
  • 2018-10-31
  • 2022-11-04
  • 2019-11-13
  • 1970-01-01
  • 1970-01-01
  • 2019-04-04
  • 2015-03-31
相关资源
最近更新 更多