Point closest to point along line

Why doesn't this function return what I expect?

I put in:
lineFrom = (0, 20, 0)
lineTo = (0, 120, 0)
c = (100, 20, 0)

I expect r to be (0, 20, 0) but I get (0, 0, 0)

u = (0, 1, 0)
v = (100, 0, 0)
w = 0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Vector closestPointAlongLine(Vector lineFrom, Vector lineTo, Vector c) {
	Vector u = toUnitVector(lineFrom, lineTo);
	Vector v = c - lineFrom;
	Vector w = dotProduct(u, V);
	Vector r((u.X * w), (u.Y * w), (u.Z * w));
	return r;
};



Vector toUnitVector(Vector c1, Vector c2) {
	coordinate c = (c1 - c2);
	float l = getLength(c);
	return Vector(c.X / l, c.Y / l, c.Z / l);
};

Vector dotProduct(vector v1, vector v2) {
	return Vector(v1.x * v2.X + v1.Y * v2.Y + v1.Z * v2.Z);
};

Last edited on
You have to return lineFrom + r instead of just r. Apart from this the code is correct (unless you try to find the closest point on line segment, not the infinite line - in the former case you should clamp the value w to be in range [0; l] to correctly handle the endpoints).
Last edited on
You are calculating the proyection, as they are ortoghonal it gives you 0
You need to add the proyection to the starting point.

By the way, take a look at valarray
Thanks guys. This has been doing my nut all day.
My 1 cent worth:

You have some upper & lower case args / member variables that should be the other way around:

1
2
Vector v = c - lineFrom;
	Vector w = dotProduct(u, V);


return Vector(v1.x * v2.X + v1.Y * v2.Y + v1.Z * v2.Z);
@TheIdeasMan - these are just standards... standards i dont conform to. dont people like u get bored of pointless posts like this?

@Everyone else - nice one
these are just standards... standards i dont conform to. dont people like u get bored of pointless posts like this?


I don't do 'pointless posts'. This one was trivial, hence the introductory
My 1 cent worth:
. Even though I sometimes post things that are trivial, it might still be of help to someone because people often miss small things.

these are just standards... standards i dont conform to.


This tells me that you have misunderstood what my post was about. Here is what I meant in more detail:

You had Vector v (lowercase v), then on the following line the function call dotProduct(u, V); (upper case V). I couldn't see a declaration of Vector V anywhere. If V was declared elsewhere - that's fine, but still it's a reasonable reason for me to make my post.

The other thing was Vector(v1.x * v2.X - again the mixed case of member variable x or X. Presumeably Vector is declared with X, Y, Z as member variables, so I am saying that v1.x might be an error.

I hope this clears up your view of my intention.
Topic archived. No new replies allowed.