计算对角线的垂直偏移 [英] calculate a perpendicular offset from a diagonal line
问题描述
我正在编写一个音乐显示程序,需要在两个音符之间画一个连线".连线是连接两个音符的曲线 - 只是为了清楚起见.
I am writing a music display program and need to draw a 'slur' between two notes. A slur is a curved line linking two notes - just to be clear.
我知道音符位置并计算曲线的起点和终点应该在哪里 - 起点 A 和终点 B.
I know the note positions and calculate where the start and end points of the curve should be - Start point A and End point B.
我现在需要获取偏移量 C,给定所需的距离,以便在二次曲线中使用.这就是我对数学公式非常有限的知识和理解的来源.
I now need to obtain the offset C, given the distance required, for use within a quadratic curve. This is where my, very, limited knowledge and understanding of maths formulae comes in.
我确实在 SO 中查看了我的答案,但所提出的解决方案要么不起作用,要么我太有限,无法正确编码.
I have indeed looked here in SO for my answer, but the solutions proposed either do not work or I am too limited to code them correctly.
有人能帮我计算一下吗,非数学形式?
Can someone help me with the calculation, in a NON mathematical form ?
推荐答案
给定线段 AB,你可以找到中点,比如 M,使用著名的中点公式 (A +B)/2
.现在计算从 B 到 A 的向量:
Given the line segment AB, you can find the midpoint, say M, using the famous midpoint formula (A + B)/2
. Now calculate the vector from B to A:
p =
绕原点旋转逆时针90°得到垂直向量
Rotate it about the origin by 90° counter-clockwise to get the perpendicular vector
n =
n = <n.x, n.y> = < ‒ p.y, p.x >
标准化:
n =
n = <n.x, n.y> / ‖n‖ where ‖n‖ = √(n.x² + n.y²) is the Euclidean Norm or length
C = L(t) = M + t n
C = L(t) = M + t n
使用这个方程 - 直线的参数形式 - 您可以找到沿垂直线(在 n 的方向上)的任意数量的点.t
是获得的点C到M的距离.当t = 0
时,你得到M,当t = 1
时,你得到离M1个单位的点strong> 沿着 n 等等.这也适用于 t
的负值,其中获得的点将在 AB 的另一侧,即朝向音符.由于 t
可以是十进制数,您可以通过改变它的值来玩弄它,以获得从 M 获得的点的所需距离和方向.
Using this equation -- parametric form of a line -- you can find any number of points along the perpendicular line (in the direction of n). t
is the distance of the obtained point, C, from M. When t = 0
, you get M back, when t = 1
, you get a point 1 unit away from M along n and so on. This also works for negative values of t
, where the points obtained will be on the opposite side of AB i.e. towards the note. Since t
can be a decimal number, you can play with it by changing its values to get the desired distance and direction of the obtained point from M.
代码,既然你说你对数学术语不感兴趣;)
Code, since you said you're not interested in the math jargon ;)
vec2d calculate_perp_point(vec2d A, vec2d B, float distance)
{
vec2d M = (A + B) / 2;
vec2d p = A - B;
vec2d n = (-p.y, p.x);
int norm_length = sqrt((n.x * n.x) + (n.y * n.y));
n.x /= norm_length;
n.y /= norm_length;
return (M + (distance * n));
}
这只是伪代码,因为我不确定您在项目中使用的向量数学库.
This is just pseudo code, since I'm not sure of the vector math library you are using for your project.
上面的粗体变量是二维向量;大写字母表示点,小写字母表示没有位置的向量
这篇关于计算对角线的垂直偏移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!