7

I can compute horizontal and vertical points, but I cant figure out how to compute distance using diagonal points. Can someone help me with this.

here's the code for my horizontal and vertical measuring:

private float ComputeDistance(float point1, float point2) 
{
        float sol1 = point1 - point2;
        float sol2 = (float)Math.Abs(Math.Sqrt(sol1 * sol1));

        return sol2;
}

protected override void OnMouseMove(MouseEventArgs e)
    {

        _endPoint.X = e.X;
        _endPoint.Y = e.Y;

        if (ComputeDistance(_startPoint.X, _endPoint.X) <= 10)
        {
            str = ComputeDistance(_startPoint.Y, _endPoint.Y).ToString();
        }
        else
        {
            if (ComputeDistance(_startPoint.Y, _endPoint.Y) <= 10)
            {
                str = ComputeDistance(_startPoint.X, _endPoint.X).ToString();
            }
        }
    }

Assuming that the _startPoint has been already set.

alt text

In this image the diagonal point is obviously wrong.

Rye
  • 2,273
  • 9
  • 34
  • 43

4 Answers4

18

You need to use Pythagoras' theorem.

d = Math.Sqrt(Math.Pow(end.x - start.x, 2) + Math.Pow(end.y - start.y, 2))
Andrew Cooper
  • 32,176
  • 5
  • 81
  • 116
6

I think you're looking for the Euclidean distance formula.

In mathematics, the Euclidean distance or Euclidean metric is the "ordinary" distance between two points that one would measure with a ruler, and is given by the Pythagorean formula.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • +1 for pointing out that there are actually many ways of calculating distance and that the Euclidean distance is probably the one wanted here. – Chris Sep 29 '10 at 10:22
3

Well you might take a look at: https://en.wikipedia.org/wiki/Pythagorean_theorem

Cœur
  • 37,241
  • 25
  • 195
  • 267
Yves M.
  • 3,330
  • 14
  • 12
0

Much time later... I'd like to add that you could use some built-in functionality of .NET:

using System.Windows;

Point p1 = new Point(x1, y1);
Point p2 = new Point(x2, y2);
Vector v = p1 - p2;
double distance = v.Length;

or simply:

static double Distance(double x1, double x2, double y1, double y2)
{
    return (new Point(x1, y1) - new Point(x2, y2)).Length;
}
heltonbiker
  • 26,657
  • 28
  • 137
  • 252