2

i know how to get Angles with atan2 between 2 Points in 2D, but how does this work in 3D?: lets say i have 3 Points A,B,C (all are SCNVector3 with x,y,z coordinates First Line Endpoints A and B 2nd Line Endpoints B and C Now i want to get the angle between the 2 Lines... (in ios Swift) I read something about the dot product and acos but somehow it does not work...

With i=0:

        var vector1 = SCNVector3((pointArray[i].x - pointArray[i+1].x), (pointArray[i].y - pointArray[i+1].y), (pointArray[i].z - pointArray[i+1].z))
        var vector2 = SCNVector3((pointArray[i+2].x - pointArray[i+1].x), (pointArray[i+2].y - pointArray[i+1].y), (pointArray[i+2].z - pointArray[i+1].z))
        var dotProduct = vector1.x * vector2.x + vector1.y * vector2.y + vector1.z * vector2.z
        var theta = acos(dotProduct)
        var tmp_winkel = GLKMathRadiansToDegrees(theta)
cheese
  • 45
  • 1
  • 6

2 Answers2

5

the dot product takes the norm (magnitude) of the vectors into account. Make sure you deal with unit vectors, or divide by the product of their norms.

import SceneKit
import simd

var vector1 = float3((pointArray[i].x - pointArray[i+1].x), (pointArray[i].y - pointArray[i+1].y), (pointArray[i].z - pointArray[i+1].z))
var vector2 = float3((pointArray[i+2].x - pointArray[i+1].x), (pointArray[i+2].y - pointArray[i+1].y), (pointArray[i+2].z - pointArray[i+1].z))
var dotProduct = dot(normalize(vector1), normalize(vector2))
var theta = acos(dotProduct)

or

var vector1 = float3((pointArray[i].x - pointArray[i+1].x), (pointArray[i].y - pointArray[i+1].y), (pointArray[i].z - pointArray[i+1].z))
var vector2 = float3((pointArray[i+2].x - pointArray[i+1].x), (pointArray[i+2].y - pointArray[i+1].y), (pointArray[i+2].z - pointArray[i+1].z))
var dotProduct = dot(vector1, vector2)
var theta = acos(dotProduct / (length(vector1) * length(vector2)))
mnuages
  • 13,049
  • 2
  • 23
  • 40
  • ah i see, forgot to do the normalize, Thanks!! Problem remaining: direction of the angle... how can i find out if it is clockwise or counterclockwise? – cheese Oct 17 '17 at 14:50
  • 1
    the cross product can help, see https://stackoverflow.com/questions/5188561/signed-angle-between-two-3d-vectors-with-same-origin-within-the-same-plane – mnuages Oct 17 '17 at 15:58
  • @mnuages I need some help on getting angles between numbers of lines with the SCNVector3 array? It will be very helpful to me. – Paras Joshi Aug 02 '21 at 10:39
1

so for getting the direction i do now (thanks mnuages for the hint):

var vectorn = cross(normalize(vector1), normalize(vector2))
if (vectorn.y > 0) { //righ hand side }
else { //left hand side}
cheese
  • 45
  • 1
  • 6