We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpPrograms › Drawing x number of points along a line
Page Index Toggle Pages: 1
Drawing x number of points along a line (Read 318 times)
Drawing x number of points along a line
Nov 18th, 2008, 7:03pm
 
I have a line with a start point (x1, y1) and an end point (x2, y2), and I want to draw a number of shapes evenly spaced along that line.  The number of shapes will vary, however.  For example, here's a very rough approximation of what I want.  The line with three dots drawn:

Code:
  .   .   .
____________


But that same line could be drawn with 7 dots:

Code:
. . . . . . .
____________


Of course, if the line were horizontal at all times, this would be easy (a matter of dividing the line length by the # of shapes), but its end points will be moving, so the line's length and angle will be changing.  So I need a way to calculate, with each frame, where to place the shapes, given the line's start and end points, and the # of shapes.

I think this involves trigonometry, but maybe there's a simpler way.  How can I loop through each shape and get the x/y value for where to plot it, each one further out along the line?

Thanks in advance for your ideas!
Re: Drawing x number of points along a line
Reply #1 - Nov 18th, 2008, 9:15pm
 
lerp() has precisely an example illustrating that...
Re: Drawing x number of points along a line
Reply #2 - Nov 18th, 2008, 9:35pm
 
Nice!  Thanks, PhiLho.

I just figured out another way, thanks to some guidance from this Java example:

http://www.java-forums.org/java-2d/10984-calculate-x-y-given-starting-angle-distance.html

The key is to use cosine to calculate the x point, and sine to calculate the y point.

Code:

//we know start and end points of line from.x, from.y and to.x, to.y
//get the angle of the line
float angle = atan2((to.y - from.y), (to.x - from.x));

//get the dist() of the line
float lineLength = dist(from.x, from.y, to.x, to.y);

//segmentLength = divide that amount by the # of shapes to be drawn
float segmentLength = lineLength / count;

//loop through, once for each shape:
for(int i = 1; i < count+1; i++) {                
     float distFromStart = segmentLength * i;
     float px = from.x + distFromStart * cos(angle);
     float py = from.y + distFromStart * sin(angle);
     point(px, py);
   }


It looks like you could accomplish the same thing without trig using lerp().  Thanks!
Page Index Toggle Pages: 1