Angle between 3 points in 3d space

后端 未结 4 1241
挽巷
挽巷 2020-12-15 07:17

I have 3 points containing X, Y, Z coordinates:

var A = {x: 100, y: 100, z: 80},
    B = {x: 100, y: 175, z: 80},
    C = {x: 100, y: 100, z: 120};
         


        
4条回答
  •  南方客
    南方客 (楼主)
    2020-12-15 07:57

    @Roger algorithm in swift

    func SCNVector3Angle(start: SCNVector3, mid: SCNVector3, end: SCNVector3) -> Double {
        let v1 = (start - mid)
        let v2 = (end - mid)
        let v1norm = v1.normalized()
        let v2norm = v2.normalized()
    
        let res = v1norm.x * v2norm.x + v1norm.y * v2norm.y + v1norm.z * v2norm.z
        let angle: Double = Double(GLKMathRadiansToDegrees(acos(res)))
        return angle
    }
    
    /**
    * Subtracts two SCNVector3 vectors and returns the result as a new SCNVector3.
    */
    func - (left: SCNVector3, right: SCNVector3) -> SCNVector3 {
        return SCNVector3Make(left.x - right.x, left.y - right.y, left.z - right.z)
    }
    
    extension SCNVector3
    {
        /**
        * Returns the length (magnitude) of the vector described by the SCNVector3
        */
        func length() -> Float {
            return sqrtf(x*x + y*y + z*z)
        }
    
        /**
        * Normalizes the vector described by the SCNVector3 to length 1.0 and returns
        * the result as a new SCNVector3.
        */
        func normalized() -> SCNVector3 {
            return self / length()
        }
    }
    

提交回复
热议问题