Feeds:
Posts
Comments

Archive for August, 2010

On the blitzbasic.com forums, Ryan Moody asks:

I know the following:

– The equation of the line L1
– The point (x1, y1)
– The perpendicular distance d
– L1 and L are parallel

However, I need to determine either:

– The equation of the line L, or
– The point (X, Y) (from which the equation of the line L can be easily derived)

Easy enough, when you think in terms of vectors.

  • Let a be the point (x1,y1) on L1. Let b be the direction of L1.
  • Find the unit vector n perpendicular to b.
  • Then the point (x,y) = a+d*n.

Here’s some BlitzMax code:

Graphics 600,600,0

Global ax#=300,ay=300# 'a point on L1
Global bx#,by# 'the direction of L1
Global d#=50 'the distance of L from L1

While Not (KeyHit(KEY_ESCAPE) Or AppTerminate())
'interaction stuff
If MouseHit(1) 'left click to place point A
ax=MouseX()
ay=MouseY()
Else 'L1 points in direction of mouse cursor - the vector B
bx=MouseX()-ax
by=MouseY()-ay
EndIf

'press up arrow to increase distance, down to decrease distance
d:+KeyDown(KEY_UP) - KeyDown(KEY_Down)
If d<0 Then d=0

'''' to find L

'first find n, a unit vector perpendicular to b
Local nx#,ny#
If by=0
'if by = 0 then we can't divide by it but the perpendicular vector is easy - it's vertical!
nx=0
ny=-Sgn(bx)
Else
'clever trick to find perpendicular vector
'the *sgn(by) bit is to make sure it's always on the right side of L1
nx=1*Sgn(by)
ny=-bx/by*Sgn(by)
'it needs to be a unit vector, so divide it by its length to end up with length 1
Local n#=Sqr(nx*nx+ny*ny)
nx:/n
ny:/n
EndIf

'make n have the length we want to make the lines the right distance apart
nx:*d
ny:*d

'now the equivalent of point A on L is the point A+N, and the direction of L is the same as that of L - B
cx = ax+nx
cy = ay+ny

'draw L1
SetColor 255,255,255
DrawLine ax-bx*500,ay-by*500,ax+bx*500,ay+by*500
DrawOval ax-4,ay-4,8,8
SetColor 255,0,0
DrawText "A",ax,ay

'draw B
SetColor 0,0,255
drawarrow ax,ay,bx,by
DrawText "B",ax+bx/2,ay+by/2

'draw L
SetColor 255,255,255
DrawLine cx -bx*500, cy -by*500, cx +bx*500, cy +by*500
DrawOval cx-4,cy-4,8,8
SetColor 255,0,0
DrawText "C",cx,cy

'draw N
SetColor 0,0,255
drawarrow ax,ay,nx,ny
DrawText "N",ax+nx/2,ay+ny/2

Flip
Cls
Wend

Function drawarrow(ax,ay,vx#,vy#)
DrawLine ax,ay,ax+vx,ay+vy

Local v#=Sqr(vx*vx+vy*vy)
vx:/v
vy:/v

'getting lazy, going to use trig
Local an#=ATan2(vy,vx)
Local px#=Cos(an+90),py#=Sin(an+90)

DrawLine ax+vx*v,ay+vy*v,ax+vx*(v-8)+px*8,ay+vy*(v-8)+py*8
DrawLine ax+vx*v,ay+vy*v,ax+vx*(v-8)-px*8,ay+vy*(v-8)-py*8
End Function

Read Full Post »