Getting the closest point on a line and return the normal

Posted By: alibaba

Getting the closest point on a line and return the normal - 12/01/15 09:39

Hi guys,

lets say I have a line and a point. I need to get the closest point on the line to that point and also the normal on that point.
How would you achieve it? I have thought on some ways, but they are pretty dirty and slow.

You can interpret the situation as a "path" and a close "entity" in a level.
Posted By: Superku

Re: Getting the closest point on a line and return the normal - 12/01/15 09:43

You could use the following function

Code:
var get_line_segment_point_dist(VECTOR* vec1, VECTOR* vec2, VECTOR* point, VECTOR* vresult, var* fac)
{
	var dist;
	double loci;
	double dot1,dot2;
	VECTOR dir1,dir2;
	
	vec_diff(dir1,vec2,vec1);
	if(vec_length(dir1) < 1)
	{
		if(vresult) vec_set(vresult,dir1);	
		if(fac) *fac = 0.5;
		dist = (vec_dist(dir1,point));
		return dist;
	}
	vec_diff(dir2,point,vec1);
	dot1 = dir1.x*(double)dir1.x+(double)(dir1.y*(double)dir1.y)+(double)(dir1.z*(double)dir1.z);
	if(dot1 > -0.001 && dot1 < 0.001) return -1; 
	dot2 = dir2.x*(double)dir1.x+(double)(dir2.y*(double)dir1.y)+(double)(dir2.z*(double)dir1.z);
	loci = dot2/dot1;
	if(loci < 0) loci = 0;
	if(loci > 1) loci = 1;
	
	vec_scale(dir1,loci);
	vec_add(dir1,vec1);
	dist = vec_dist(dir1,point);	
	if(vresult) vec_set(vresult,dir1);	
	if(fac) *fac = loci;
	
	return dist;
}



and use

vec_diff(normal,point,vresult);
vec_normalize(normal,1);

to get the desired normal - assuming I got your issue correctly.
Posted By: alibaba

Re: Getting the closest point on a line and return the normal - 12/01/15 14:52

That's exactly what I wanted to achieve, thanks a bunch! laugh
Posted By: Anonymous

Re: Getting the closest point on a line and return the normal - 12/01/15 17:16

@Superku - Nice!
© 2024 lite-C Forums