Sign in to follow this  
Promit

Two points to line equation (standard form)

Recommended Posts

This should be damned simple, but I'm having problems anyway. I started with the equation y - bx = c and came up with the following code (VB.NET):
    Public Function CalcLine( p As PointF, q As PointF ) As Line
        Dim dx As Single = q.X - p.X
        Dim dy As Single = q.Y - p.Y

        Dim Ret As Line
        Ret.n.X = -dx / dy
        Ret.n.Y = 1.0f
        Normalize( Ret.n )
        Ret.c = p.Y - (dy/dx) * p.X
        Return Ret
    End Function



This works. But the problem is that the direction that the normal points is "wrong". I want the result to be such that if you are standing in between p and q, and facing in the direction of the normal, p will be on your left and q will be on your right, no matter what the signs of dx and dy. (Put another way, the normal should always point counter clockwise.) Oh, and there's one last little catch: this is drawn in a GDI+ window, so +y goes downwards. You'd probably be better served to consider it as looking down on the XZ plane rather than the XY plane. Anyway, after some toying around, I came up with the following fix:
    Public Function CalcLine( p As PointF, q As PointF ) As Line
        Dim dx As Single = q.X - p.X
        Dim dy As Single = q.Y - p.Y
        Dim dxAbs As Single = Math.Abs( dx )

        Dim Ret As Line
        Ret.n.X = dy / dxAbs
        Ret.n.Y = -dxAbs / dx
        Normalize( Ret.n )
        Ret.c = p.Y - (dy/dx) * p.X
        Return Ret
    End Function



This works. But I'm generally wary of using abs and sign calculations explicitly in mathematical calculations like so, and I don't like this fix. I suspect I'm missing something very simple.

Share this post


Link to post
Share on other sites
This should work plus it avoids the problem when dy == 0.

Ret.n.X = dy
Ret.n.Y = -dx
Normalize( Ret.n )

Note: this solution comes from the standard 2D rotation formulas and the fact that cos(pi/2) = 0 and sin(pi/2) = 1.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this