i have line segment , circle in processing sketch. want center of circle, point q, find closest point, p, on line segment , circle move towards it. i'm not quite sure how code (in processing), suggestions great! thanks! code far:
int xpos1 = 200; int ypos1 = 200; int xp1 = 50; int yp1 = 50; int xp2 = 350; int yp2 = 50; void setup() { size(400, 400); strokeweight(2); line(xp1, yp1, xp2, yp2); strokeweight(1); } void draw() { drawcircle(); } void drawcircle() { fill(50, 120, 120); //circle ellipse(xpos1, ypos1, 75, 75); //circle center ellipse(xpos1, ypos1, 7, 7); fill(255); text("q", xpos1 + 15, ypos1 + 5); fill(50, 120, 120); }
the projection of point onto line follows:
start line of form x = + t * n , point p.
the vector compontent representing nearest point on line point p is:
(a - p) - ((a - p) dot n)n
so have: p + (a - p) - ((a - p) dot n)n
after simplification have: - ((a - p) dot n)n
note ((a - p) dot n) n vector component represents position along line nearest point beginning (i.e. nearest point p a)
let's use pvector
s make life bit easier.
pvector p = new pvector(200, 200); pvector = new pvector(50, 50); pvector b = new pvector(350, 50); pvector n = new pvector(350, 50); // |p2 - p1| void setup() { size(400, 400); strokeweight(2); strokeweight(1); // initialize our normalized (unit length) line direction n.sub(a); n.normalize(); } void draw() { drawcircle(); } pvector getnearestpointonline(pvector p, pvector a, pvector n){ // notation turns computation inside out, // equivalent above equation pvector q = pvector.mult(n, -pvector.sub(a, p).dot(n)); q.add(a); return q; } void drawcircle() { // lets draw here can see background(255, 255, 255); line(a.x, a.y, b.x, b.y); fill(50, 120, 120); //circle // note: may require hooking mouse move event handler p.x = mousex; p.y = mousey; pvector q = getnearestpointonline(p, a, n); ellipse(q.x, q.y, 75, 75); //circle center ellipse(q.x, q.y, 7, 7); fill(0); // make text visible on white background text("q", q.x + 15, q.y + 5); //fill(50, 120, 120); }
reference: https://en.wikipedia.org/wiki/distance_from_a_point_to_a_line#vector_formulation
Comments
Post a Comment