微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

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

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

如果是,那么SceneKit函数用于添加像SCNMatrix4Mult这样的矩阵用于乘法,或者我必须自己使用Metal编写它?

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

我不想使用GLKit.

enter image description here

解决方法

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

节点层次结构是

parentNode
    |
    |----BoxNode // rotated around Y (vertical) axis

使用转换矩阵

沿自己的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);

// 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;

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

另外一个选项:

使用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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐