I'm not quite sure what I'm doing wrong, as this should be fairly simple... I have 2 given points plus X from the third - and now I need Y from that third line.
That's a really simple equation: y = mx + b. But because I can't use this in my C#-program (well, I'm sure there's a library for that, but performance matters here), I'm trying to "write the formula out".
My function looks like this:
public static float GetY(Vector2 point1, Vector2 point2, float x)
{
var m = (point2.Y - point1.Y) / (point2.X + point1.Y);
var b = point1.Y - (m * point1.X);
return m*x + b;
}
Now something in this formula is wrong, because sometimes I don't get the right value. Do you have any idea what I'm doing wrong?
In your posted code, you seem to have made a typo. This:
var m = (point2.Y - point1.Y) / (point2.X + point1.Y);
...should be:
var m = (point2.Y - point1.Y) / (point2.X - point1.X);
You want this:
public static float GetY(Vector2 point1, Vector2 point2, float x)
{
var dx = point2.X - point1.x; //This part has problem in your code
if (dx == 0)
return float.NaN;
var m = (point2.Y - point1.Y) / dx;
var b = point1.Y - (m * point1.X);
return m*x + b;
}
I would have thought that:
var m = (point2.Y - point1.Y) / (point2.X + point1.Y);
should be
var m = (point2.Y - point1.Y) / (point2.X - point1.X);
Gradient is the delta in Y divided by the delta in X.
You've put point1.y twice in the formula for m. Additionally as noticed by Jacob it should be a minus!
Think you want
var m = (point2.Y - point1.Y) / (point2.X - point1.X);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With