Angle Between Two Points

Started by
11 comments, last by Dmytry 18 years, 7 months ago
i dont remember the vb code script... so ill just paste it in.


Private Function getAngle(ByVal x1 As Single, ByVal y1 As Single, ByVal x2 As Single, ByVal y2 As Single)
'Const PI = 3.14159
'Const RAD = PI / 180
'Const DEG = 180 / PI

On Error Resume Next

Dim xLength As Single
Dim yLength As Single

xLength = x1 - x2: yLength = y1 - y2

If xLength = 0 And yLength = 0 Then Exit Function
If xLength = 0 And yLength > 0 Then getAngle = 0
If yLength = 0 And xLength < 0 Then getAngle = 90
If xLength = 0 And yLength < 0 Then getAngle = 180
If yLength = 0 And xLength > 0 Then getAngle = 270


getAngle = Atn(yLength / xLength)
getAngle = getAngle * DEG

If xLength < 0 Then
getAngle = getAngle + 90
ElseIf xLength > 0 Then
getAngle = getAngle + 270
End If

End Function
-----------------www.stevemata.com
Advertisement
Here is a better one

Private Function FindAngle(intX1 As Single, intY1 As Single, intX2 As Single, intY2 As Single) As Single

Dim sngXComp As Single
Dim sngYComp As Single

sngXComp = intX2 - intX1
sngYComp = intY1 - intY2
If sngYComp > 0 Then FindAngle = Atn(sngXComp / sngYComp)
If sngYComp < 0 Then FindAngle = Atn(sngXComp / sngYComp) + PI

End Function
-----------------www.stevemata.com
you forgot "if sngYComp == 0 crash and burn".
I would do that:
Private Function FindAngle(intX1 As Single, intY1 As Single, intX2 As Single, intY2 As Single) As SingleDim sngXComp As SingleDim sngYComp As SingleX = intX2 - intX1Y = intY1 - intY2If abs(X)<1E-10 and abs(Y)<1E-10 [something like FindAngle = 0; Exit Function]If abs(Y)>abs(X) Then If Y > 0 Then FindAngle = Atn(X / Y) Else FindAngle = Atn(X / Y) + PI End IfElse If X > 0 Then FindAngle = 0.5*PI - Atn(Y / X) Else FindAngle = -0.5*PI - Atn(Y / X) End IfEnd IfEnd Function

General idea is to find which value is bigger and divide by it. This way, various errors and imprecisions are smaller.
Note: I have no idea about actual VB syntax. Probably it will not compile, you need to edit it.

BTW, it is made to give same direction and origin of angle as your code. It might be not what you really want.[grin]
Also, it probably will give out somewhat messy result in sense that in some quadrants it will give angle and in other it will give angle+2*pi.
To make result be always in range -pi to pi you can add this in the end:
if angle>pi then angle=angle-2*pi else if angle<-pi angle=angle+2*pi

[Edited by - Dmytry on September 26, 2005 2:04:37 AM]

This topic is closed to new replies.

Advertisement