将SCNNode旋转以面向指定点

4

我想让我的物体(SCNNode)面向它移动的点进行旋转。目前我只在x和y轴上移动,我尝试过以下方法:

    // Action to move node
    let action1 = SCNAction.moveTo(SCNVector3(x: 4.0, y: 0.0, z: 6.0), duration: 3)
    // Get the tan angle:
    let angle = CGFloat(atan2(z, x))
    if angle - previousAngle > Pi {
        playerAngle += 2 * Pi
    } else if previousAngle - angle > Pi {
        playerAngle -= 2 * Pi
    }
    previousAngle = angle
    playerAngle = angle * RotationBlendFactor + playerAngle * (1 - RotationBlendFactor)
    let rot = playerAngle - 90 * DegreesToRadians
    flyNode.rotation = SCNVector4(x: 0, y: 1, z: 0, w: Float(rot))

它适用于某些目标点,但不适用于所有目标点。

我尝试将SCNLookAtConstraint添加到限制数组中,它可以完美地旋转我的节点,但它会停止我的移动动画:

    let targerNode = SCNNode()
    targerNode.position = SCNVector3(x: -4.0, y: 0.0, z: -2.0)
    let con = SCNLookAtConstraint(target: targerNode)
    flyNode.constraints = [con]        
    let action1 = SCNAction.moveTo(SCNVector3(x: 4.0, y: 0.0, z: -2.0), duration: 3)

你能帮我解决这个问题吗?


听起来和我遇到的问题很相似。看看这个能否帮到你:http://stackoverflow.com/questions/35384392/swift-orient-y-axis-toward-another-point-in-3-d-space - bpedit
@bpedit 谢谢,这正是我想要的。 - Greg
2个回答

0

最简单的解决方案,虽然可能不是最优雅的,就是将你的 moveTo SCNAction 应用于一个节点,并将 SCNLookAtConstraint 应用于该节点的子节点。这样应当可以让两个操作不冲突。


0

尝试使用这个:(它是Objective-C,但应该很容易转换)

float x, z;// these are your vars you assign these so you can delete this line


float offset = 0; // use this to offset your final output
                  // because your output might be off by 
                  // a quarter of a turn or so, or more
                  // but once you got the offset right
                  // than it will stay right
float aQuarterOfAturn = 1.570795;// since scenekit uses radians
                                 // this needs to be pi/2
                                 // if it was degrees it would be 90


if (x < 0) {
    offset += aQuarterOfAturn;// turn it to compensate for the lack of negetive x
    x *= -1;// convert x to positive so we can calculate it
}
if (z < 0) {
    offset += aQuarterOfAturn;// turn it to compensate for the lack of negetive z
    z *= -1;// convert z to positive so we can calculate it
}

xzDelta = x + z// add x and z

zPercent = z * 100 / xzDelta // so we can calculate how much percent z is

yRot = aQuarterOfAturn * zPercent / 100 // and finally convert it to a rotation

yRot += offset // add the offset and you can implement the rotation now
// a note, this code has not been tested you may need to offset it (above)
// and possibly multiply it by negitive 1

// if it works fine but the rotation is off by however many degrees than just offset it

// if it works fine but your move up and it rotates down than multiply it by -1

请告诉我它是如何工作的!


最后一行会像这样子吗? SCNAction.rotateTo(x: x, y: yRot, z: z, duration: 1) - user287474

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接