working out the point positions along a straight line?

coolpjmartin

Member
Joined
Aug 8, 2006
Messages
9
Programming Experience
Beginner
Help needed Calculating New points along a straight line:

I need some help working out the point positions along a straight line:

I will try to explain what I am doing:

I have two points (x1, y1) and (x2,y2) and have a straight line between the 2 points, from this I can work out the distance between the 2 points lets say it is 50.
What I want to do is increase or decrease the length of the line by a predefined amount lets say 10.
So If I increase the line length by 10 (from 50 to 60), What I want to work out is what point(x3,y3) would be at the end of the increased line.
Hope this makes sense.
I have tried to work out the new point using the angle but it does not work correctly, it does not seems to produce a perfectly straight line and the angle from point (x1,y1) to the new (x3,y3) is not the same as the angle from point (x1,y1 to x2,y2).

This is what I have tried:
:I work out the angle
aAngle =Math.Atan((Y2 – Y1) / (X2 – X2))

:get the length of the line and increase by 10
nChngX = Math.Pow((X1 –X2), 2))
nChngY = Math.Pow((Y1 – Y2), 2))
nChng = Math.Sqrt(nChngX + nChngY) + 10

:work out the new points (x3,y3)
X3 = CSng((Math.Cos(aAngle) * nChng))
Y3 = CSng(CSng((Math.Sin(aAngle) * nChng)))

If someone could post some sample code, in either c# or vb.net that would be much appreciated.
 
This will give you a start:
VB.NET:
Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
    e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
    
    Dim p1 As New PointF(40, 50)
    Dim p2 As New PointF(100, 60)
    Dim aAngle = Math.Atan(((p1.X - p2.X)) / ((p1.Y - p2.Y)))
    Dim len = 10
    Dim cos = CSng(Math.Cos(aAngle) * len)
    Dim sin = CSng(Math.Sin(aAngle) * len)
    Dim p3 As New PointF(sin + p2.X, cos + p2.Y)

    e.Graphics.DrawLine(Pens.Red, p2, p3)
    e.Graphics.DrawLine(Pens.Blue, p1, p2)
    Me.Text = String.Format("l1: {0} l2: {1}", LineLength(p1, p2), LineLength(p2, p3))
End Sub

Function LineLength(ByVal p1 As PointF, ByVal p2 As PointF) As Single
    Return CSng(Math.Sqrt(Math.Pow((p1.X - p2.X), 2) + Math.Pow((p1.Y - p2.Y), 2)))
End Function
 
Back
Top