绕轴旋转 SCNVector3

Joh*_*alo 4 trigonometry linear-algebra ios scenekit

这可能更像是一个线性代数问题,但是假设我有一个 SCNVector,并且我想要一个新的 SCNVector,它与围绕 y 轴(或任何相关轴)的原始 SCNVector 成一定角度。所以理想情况下:

extension SCNVector3 {  
    // assume dot, cross, length, +, - functions are available.
    enum Axis {
        case x, y, z
    }
    func rotatedVector(aroundAxis: Axis, angle: Float) -> SCNVector3 {
        // code from smart person goes here
    }
}
Run Code Online (Sandbox Code Playgroud)

例如(0,0,-1).rotatedVector(aroundAxis: y, angle: pi/2) = (1,0,0)

谢谢!

OLE*_*DEV 5

尝试使用四元数https://developer.apple.com/documentation/accelerate/working_with_quaternions

extension SCNVector3 {
    enum Axis {
        case x, y, z
        
        func getAxisVector() -> simd_float3 {
            switch self {
            case .x:
                return simd_float3(1,0,0)
            case .y:
                return simd_float3(0,1,0)
            case .z:
                return simd_float3(0,0,1)
            }
        }
    }

    func rotatedVector(aroundAxis: Axis, angle: Float) -> SCNVector3 {
        /// create quaternion with angle in radians and your axis
        let q = simd_quatf(angle: angle, axis: aroundAxis.getAxisVector())
        
        /// use ACT method of quaternion
        let simdVector = q.act(simd_float3(self))
        
        return SCNVector3(simdVector)
    }
}
Run Code Online (Sandbox Code Playgroud)

使用:

let a = SCNVector3(5,0,0)

let b = a.rotatedVector(aroundAxis: SCNVector3.Axis.y, angle: -.pi/2)

// SCNVector3(x: 0.0, y: 0.0, z: 5.0)
Run Code Online (Sandbox Code Playgroud)

您还可以围绕任何向量旋转:

let simdVector = q.act(simd_normalize(simd_float3(x: 0.75, y: 0.75, z: -0.2)))
Run Code Online (Sandbox Code Playgroud)