Using the Equation of a Straight Line in Visual Basic
The equation of a straight line has the general form
y = mx + c;
where m is the slope and c
is the intercept on the y-axis.
For a vertical line, x is constant and for
a horizontal line, y is constant.
Generating Straight Lines for Visual Basic
Given any 2 points (x1, y1)
and (x2, y2); we'll have:
|
y2 - y1 |
= |
y - y1 |
x2 - x1 |
x - x1 |
⇒ y = ( |
y2 - y1 |
) x + |
x2y1 - x1y2 |
x2 - x1 |
x2 - x1 |
Comparing this to the general equation of a straight line,
i.e. y = mx + c
m = |
y2 - y1 |
x2 - x1 |
& |
c = |
x2y1 - x1y2 |
x2 - x1 |
Say we are to find the equation for the line represented
by the arbitrary points (50, 50) and (200, 100):
m = |
100 - 50 |
= |
50 |
= |
1 |
200 - 50 |
150 |
3 |
& |
c = |
200(50) - 50(100) |
= |
10000 - 5000 |
200 - 50 |
150 |
= |
5000 |
= |
100 |
150 |
3 |
Hence,
y = 1/3x + 100/3
or
3y = x + 100
Code to Animate a Graphic Object by a Line Equation in Visual Basic
To make a graphic (dot) travel by the equation of a line,
continuously increment x, and use the equation to
get the corresponding y value.
Let's do so with the above equation representing points
(x1, y1) = (50, 50)
and (x2, y2) = (100, 200).
Create a new class;
Call it StraightLine.
Type out the adjoining VB.Net code for animating an image body through
the path of a straight line.
Dymetric class
Public Class Dymetric
Private line_motion As New StraightLine
Private do_simulation = False
Public Sub decideAction(sender As Object, g As Graphics, click_check As Boolean)
If do_simulation And click_check Then
line_motion.play(sender, g)
do_simulation = False
Else
line_motion.prep(sender, g)
do_simulation = True
End If
End Sub
End Class
VB.Net code for StraightLine class
Public Class StraightLine
Private x1, y1, x2, y2, x, y As Integer
Private m, c As Double
Private Const dotDIAMETER = 10
Dim dot_colour As New System.Drawing.SolidBrush(System.Drawing.Color.Yellow)
Dim bg_colour As New System.Drawing.SolidBrush(System.Drawing.Color.LightGray)
Public Sub prep(sender As Object, g As Graphics)
x1 = 10
y1 = 70
x2 = sender.Width - 50
y2 = sender.Height - 50
x = x1
y = y1
m = (y2 - y1) / (x2 - x1)
c = (x2 * y1 - x1 * y2) / (x2 - x1)
g.FillRectangle(bg_colour, 0, 60, sender.Width, sender.Height)
g.FillEllipse(dot_colour, x, y, dotDIAMETER, dotDIAMETER)
End Sub
Public Sub play(sender As Object, g As Graphics)
Do While x < sender.Width - dotDIAMETER
y = CInt(Math.Ceiling(m * x + c))
g.FillEllipse(dot_colour, x, y, dotDIAMETER, dotDIAMETER)
x += 20
Threading.Thread.Sleep(50)
Loop
End Sub
End Class