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 › nearest point
Page Index Toggle Pages: 1
nearest point (Read 786 times)
nearest point
Nov 4th, 2005, 8:38pm
 
if anyone knows how to solve this problem.

if i have a triangle or square drawn on stage and if i bring mouse towards it, how to make the line drawn along the nearest side of the shape.

basicaly, i want to redraw with the mouse the pre-drawn shape along the sides of it.
is there a special math formula has to be involved?
i am very new to programming.


thanks.

misha..
Re: nearest point
Reply #1 - Nov 18th, 2005, 8:46am
 
To clarify

you want to draw a line from the mouse to the closest point on a geometric shape, say... a square or triangle?
Re: nearest point
Reply #2 - Nov 20th, 2005, 5:23pm
 
An idea:

Quote:


// distancia mínima
// perpendicular

int dim=500;
int center=dim/2;

float lineOx; // x origin
float lineOy; // y origin
float lineEx; // x end
float lineEy; // y end

float intersecx,intersecy; // coord intersection
float ax,ay;
float ff;
float lineMag;

void setup()
{
 size(dim,dim);
 background(255);

 lineOx=random(dim-50);
 lineOy=random(dim-50);
 lineEx=random(dim-50);
 lineEy=random(dim-50);

}

void draw()
{
 background(255);
 doIt();
}

float d(float _x1, float _y1, float _x2, float _y2)
{
 return sqrt(sq(_x2-_x1)+sq(_y2-_y1));
}

void doIt()
{
 ax=mouseX;
 ay=mouseY;
 
 stroke(190);
 fill(255);
 
 lineMag = d(lineOx,lineOy,lineEx,lineEy);
 line(lineOx,lineOy,lineEx,lineEy);
 
 ellipseMode(CENTER);
 ellipse(lineOx,lineOy,10,10);
 ellipse(lineEx,lineEy,10,10);
 ellipse(ax,ay,10,10);
 
 ff =  (( ( ax - lineOx ) * ( lineEx - lineOx ) ) + ( ( ay - lineOy ) * ( lineEy - lineOy ) )) / ( lineMag * lineMag );
 
 if( ff < 0.0 || ff > 1.0 ){
   return;  // doesn't fall within the line: line (if you want) to the nearest vertex
 } else {
   intersecx = lineOx + int(ff * (lineEx - lineOx));
   intersecy = lineOy + int(ff * (lineEy - lineOy));
   line(ax,ay,intersecx,intersecy);
       fill(255);
   ellipse(ax,ay,10,10);
   noStroke();
   fill(255,0,0);
   ellipse(intersecx,intersecy,2,2);
 }

}



It depends if you want doIt every side...
But you'll must work it.
One saludo.
Nach.
Page Index Toggle Pages: 1