如何使用 SCNTransformConstraint 来限制节点的 Z 值?

How to use an SCNTransformConstraint to restrict the Z value of a node?

我似乎无法弄清楚如何使用 SCNTransformConstraint 来限制节点的 Z 值。这是我目前所拥有的。

        let constraint = SCNTransformConstraint(inWorldSpace: true, withBlock:{
            node, matrix in

            var newMatrix = matrix
            let currentNode = node as SCNNode
            if (currentNode.presentationNode().position.z > 0.0) {
                newMatrix.m43 = 0.0
            }

            return newMatrix
        })

    ship.constraints = [constraint]

根据上述约束,当我对其 physicsBody 施加力时,ship 不会移动。任何帮助将不胜感激。

是的。这个也让我有点难过。

问题出在矩阵上。根据Developer documentation关于SCNMatrix4(矩阵)的说法:

If the node is affected by an in-progress animation, this value reflects the currently visible state of the node during the animation (rather than its target state that will be visible when the animation completes).

而不是这个:

var newMatrix = matrix

你真的想要:

var newMatrix = node.transform

这似乎是要应用于节点的当前变换。

我知道这是一个老问题,但它在 SCNTransformConstraint 的搜索结果中排名靠前。嘿,迟到总比不到好,对吧?

这对我有用,可以将 SCNCameraController 约束到网格的边界:

    let constraint = SCNTransformConstraint.positionConstraint(inWorldSpace: false, with: { (node, position) -> SCNVector3 in
        var constrainedPosition = position
        if position.x < gridMinX {constrainedPosition.x = gridMinX; node.position.x = gridMinX}
        if position.x > gridMaxX {constrainedPosition.x = gridMaxX; node.position.x = gridMaxX}
        if position.z < gridMinZ {constrainedPosition.z = gridMinZ; node.position.z = gridMinZ}
        if position.z > gridMaxZ {constrainedPosition.z = gridMaxZ; node.position.z = gridMaxZ}
        return constrainedPosition

    })
    sceneView.pointOfView?.constraints = [constraint]