Need help plotting a line segment, is it possible?

Hello,

Currently i am working on a program that will find the actual distance between two points on a grid. It also determines the angle of the line segment in degrees. Now, i need it to be able to find any other points on or near the line. It will be running in a loop to find each additional point sequentially until all the points have been plotted. Unfortunately, I am not entirely sure how this is done. So far, I think that I could develop an algorithm that converts the angle into a ratio of vertical movements to horizontal ones. Please tell me if I am on the right track. I have only been programming in c++ for a few months so any tips are greatly appreciated.
Last edited on
I think you should start using OpenGL or DirextDraw/3D; the console will simply be too hard to work with when you're drawing lines and performing more complex operations.
Thanks for the advice, I was planning on learning to render eventually anyway. I will look into both, but which one would you reccomend?
I'm currently doing OpenGL myself.

I've read that D3D/Draw is specifically aimed at games, whilst OpenGL is more used in professional contexts. In addition, OpenGL is open source and cross-platform. Thus I recommend OpenGL, but don't put too much weight on it; I have never tried Direct*.
Let the ends of the line segment be a and b

Let p be a point anywhere else

The nearest point to p on the line defined by a,b is

q = [ (b-a).(p-a)/|b-a|^2 ] (b-a) + a

These are all vectors . means dot product | | means modulus, i.e. size of vector b-a

One you have q you can find the distance of p from the line = |q-p|

Its a good idea to use a vector class for this sort of work, then your equation will look similar to that shown - rather than a lot of x's and y's
I am assuming that your formula would have to be used twice, once for the X coordinate and once for Y coordinate? Or is this where the vector class comes in?
Last edited on
Google "bresenham's line algorithm".
Its a vector formula, all of a, b, p, q are vectors

set c = ( (bx-ax)(px-ax)+(by-ay)(py-ay) ) / ( (bx-ax)^2 + (by-ay)^2 )

then

qx = c * (bx-ax) + ax
qy = c * (by-ay) + ay

Topic archived. No new replies allowed.