如何在SceneKit中移动旋转的SCNNode?

Mar*_*arc 7 vector matrix scenekit swift metal

下图显示了一个旋转的框,应该在X和Z轴上水平移动.Y应该不受影响以简化方案.盒子也可以是相机的SCNNode,所以我猜这个投影在这一点上没有意义.

所以我们要说我们想要沿着红色箭头的方向移动盒子.如何使用SceneKit实现这一目标?

红色箭头表示方框的-Z方向.它还向我们展示了它与摄像机的投影或与网格显示为深灰色线条的全局轴不平行.

我的最后一种方法是平移矩阵和旋转矩阵的乘积,它产生一个新的变换矩阵.我是否必须将当前变换添加到新变换中?

如果是的话,SceneKit函数在哪里添加矩阵就像SCNMatrix4Mult乘法一样,或者我必须自己使用Metal编写它?

如果不是,我错过了矩阵计算?

我不想利用GLKit.

在此输入图像描述

Sul*_*vus 12

所以我的理解是你想要沿着它自己的X轴移动Box节点(而不是它的父X轴).并且因为Box节点被旋转,其X轴未与其父节点对齐,因此您在转换两个坐标系之间的平移时遇到问题.

节点层次结构是

parentNode
    |
    |----boxNode // rotated around Y (vertical) axis
Run Code Online (Sandbox Code Playgroud)

使用转换矩阵

沿自己的 X轴移动boxNode

// First let's get the current boxNode transformation matrix
SCNMatrix4 boxTransform = boxNode.transform;

// Let's make a new matrix for translation +2 along X axis
SCNMatrix4 xTranslation = SCNMatrix4MakeTranslation(2, 0, 0);

// Combine the two matrices, THE ORDER MATTERS !
// if you swap the parameters you will move it in parent's coord system
SCNMatrix4 newTransform = SCNMatrix4Mult(xTranslation, boxTransform);

// Allply the newly generated transform
boxNode.transform = newTransform;
Run Code Online (Sandbox Code Playgroud)

请注意:当矩阵相乘时,顺序很重要

另外一个选项:

使用SCNNode坐标转换功能,看起来更直接

// Get the boxNode current position in parent's coord system
SCNVector3 positionInParent = boxNode.position;

// Convert that coordinate to boxNode's own coord system
SCNVector3 positionInSelf = [boxNode convertPosition:positionInParent fromNode:parentNode];

// Translate along own X axis by +2 points
positionInSelf = SCNVector3Make(positionInSelf.x + 2,
                                positionInSelf.y,
                                positionInSelf.z);

// Convert that back to parent's coord system
positionInParent = [parentNode convertPosition: positionInSelf fromNode:boxNode];

// Apply the new position
boxNode.position = positionInParent;
Run Code Online (Sandbox Code Playgroud)