Positioning along a line

Started by
1 comment, last by awesomefox5 12 years, 5 months ago
Hello. I'm currently working on a small project in XNA, and I've come to an issue I'd like to question. I'm guessing I'm just overlooking something or I'm being too complicated or something, but here's my issue. I have a line, AC, where A, C, and the gradient, can all change (A is fixed at the centre of a character and C is at the coordinates of the mouse). I can obviously calculate the gradient of the line with dy/dx. Heres my problem. I need another point, B, on the line to always stay the same distance along the line from A, while still moving with the rest of the line. For example, if AC's was horizontal, moving C to the right or left would not change B's position. However, if C where to be moved up or down, B would move accordingly, staying on the gradient of the line. There's an image attached,which gives an example where the distance AB needs to stay constant. Any help with this would be appreciated, and any other suggestions on how to get round this would likewise be appreciated. Thanks :)
Advertisement

B = ((C-A) / length(C-A)) * DistanceToB + A


In other words, you calculate the vector C-A and the length of said vector, divide the vector by the length (to normalize it to unit length), mutiply the vector by the distance from A that you want B to lie at, then add the result to A to get the offset position. In pseudocode:


Vx = Cx - Ax
Vy = Cy - Ay
Length = sqrt(Vx*Vx + Vy*Vy)
Vx /= Length
Vy /= Length

Bx = Ax + Vx * DistanceToB
By = Ay + Vy * DistanceToB
Ah, thank you so much, that makes sense. I was puzzling over this for quite a while. Thanks again.

This topic is closed to new replies.

Advertisement