使用scenekit和swift将模型旋转到面向3d的方向 - Boids实现

问题描述 投票:1回答:1

我正在使用Swift和Scenekit实现boids模拟。实现模拟本身是相当直接的,但是我无法让我的模型面向它们飞行的方向(至少所有时间和正确)要查看完整的项目,你可以在这里得到它(https://github.com/kingreza/Swift-Boids

以下是我正在做的旋转模型以面向它们的方向:

func rotateShipToFaceForward(ship: Ship, positionToBe: SCNVector3)
  {
    var source = (ship.node.position - ship.velocity).normalized();

    // positionToBe is ship.node.position + ship.velocity which is assigned to ship.position at the end of this call
    var destination = (positionToBe - ship.node.position).normalized();

    var dot = source.dot(destination)

    var rotAngle = GLKMathDegreesToRadians(acos(dot));
    var rotAxis = source.cross(destination);

    rotAxis.normalize();

    var q = GLKQuaternionMakeWithAngleAndAxis(Float(rotAngle), Float(rotAxis.x), Float(rotAxis.y), Float(rotAxis.z))

    ship.node.rotation = SCNVector4(x: CGFloat(q.x), y: CGFloat(q.y), z: CGFloat(q.z), w: CGFloat(q.w))


}

以下是他们现在的行为方式

https://youtu.be/9k07wxod3yI

swift 3d quaternions scenekit
1个回答
1
投票

帮助原始提问者三年太晚了,原来的YouTube视频已经不见了,但你可以在项目的GitHub page上看到一个。

原始Boids代码存储方向作为boid局部坐标空间的三个基础向量,可以将其视为3x3旋转矩阵的列。每个帧的行为“转向力”将作用于当前速度以产生新的速度。假设“速度对齐”,这个新速度与新的前向(z)向量平行。它做了旧的向上(y)向量和新的向前向量的交叉乘积,以产生新的侧向量。然后它越过新的一面向前以获得一个新的向量。仅供参考,here is the code for that in OpenSteer

因为看起来你想要方向作为四元数,所以你的四元数类可能有一个构造函数,它以旋转矩阵作为参数。

© www.soinside.com 2019 - 2024. All rights reserved.