Angle between two lines

Blitz3D Forums/Blitz3D Beginners Area/Angle between two lines

CyberHeater(Posted 2004) [#1]
Help. I'm stuck - again :(

How can I tell the difference in angle between 2 lines defined by x1,y1 to x2,y2 (line 1) and x3,y3 to x4,y4 (line 2).

A code snippet or function would be very useful.

Thanks.


big10p(Posted 2004) [#2]
The ATan2(y,x) function returns the angle of a line (note the parameter order is y,x not x,y). Try the following function:

Function line_angle_dif(x1,y1,x2,y2,x3,y3,x4,y4)
	Return ATan2(y2-y1,x2-x1)-ATan2(y4-y3,x4-y3)
End Function


Note that this will return 180 for parallel lines that are drawn in different directions, e.g.

<---------* *--------->

* = Starting points of lines

If this is not what you want, you will have to modify the function appropriately.


Bill Sims(Posted 2004) [#3]
Depending upon what you are using this for, sometimes there are optimizations that you can use.

For example, if you are just going to use this angle for cosine (or even sine), you can using the following:
Function cosAngle( x1, y1, x2, y2, x3, y3, x4, y4 )
    dx1 = x2-x1
    dy1 = y2-y1
    dx2 = x4-x3
    dy2 = y4-y3
    Return (dx1 * dx2 + dy1 * dy2 ) / Sqr( dx1*dx1 + dy1*dy1 ) / Sqr(dx2*dx2 + dy2*dy2)
End Function


In my timing tests (testing 1,000,000 segment pairs), I found this function ran in one-third of the time of the previous post once you've taken the cosine of the returned angle.

I'm not being critical of your question, but sometimes the context of the question being asked might result in a more efficient answer.

Good luck!


CyberHeater(Posted 2004) [#4]
Thanks Guys. Both look good.