Comprobar si un punto se encuentra entre dos puntos en línea recta

En ocasiones puedes necesitar saber si un punto está en una recta, mejor dicho, entre dos puntos de una recta. Esto nos serviría para saber si estamos sobre el borde de un contorno, por ejemplo.

A continuación mostramos una sencilla función para conocer el caso. La función se basa en controlar las distancias entre esos puntos. Utilizaremos la clase Point3D ya conocida para los cálculos.

        /// <summary>

        /// Establece si un punto está entre dos puntos en línea recta

        /// </summary>

        /// <param name=”pt“>Punto a comprobar</param>

        /// <param name=”StartPoint“>Punto inicial del segmento</param>

        /// <param name=”EndPoint“>Punto final del segmento</param>

        /// <returns></returns>

        public static bool PointInLine(Point3D pt, Point3D StartPoint, Point3D EndPoint,

                                       int precision)

        {

            double num1 = EndPoint.DistanceTo(StartPoint);

            double num2 = StartPoint.DistanceTo(pt);

            double num3 = num2 + EndPoint.DistanceTo(pt);

            return Math.Abs(num1 – num3) == 0;

        }

Para ponerlo a prueba puedes construir un formulario parecido al siguiente:

A continuación el código para los eventos de los controles del formulario.

        private void txtPt1X_KeyPress(object sender, KeyPressEventArgs e)

        {

            TextBox tb = sender as TextBox;

            string antT = tb.Text;

            string t = tb.Text;

            e.Handled = MyClase.OnlyNumbers(e.KeyChar.ToString(), true, ref t);

            if (antT != t)

            {

                tb.Text = t;

                tb.SelectionStart = tb.Text.Length;

            }

        }

 

        private void txtPt1Y_KeyPress(object sender, KeyPressEventArgs e)

        {

            TextBox tb = sender as TextBox;

            string antT = tb.Text;

            string t = tb.Text;

            e.Handled = MyClase.OnlyNumbers(e.KeyChar.ToString(), true, ref t);

            if (antT != t)

            {

                tb.Text = t;

                tb.SelectionStart = tb.Text.Length;

            }

        }

 

        private void txtPt1Z_KeyPress(object sender, KeyPressEventArgs e)

        {

            TextBox tb = sender as TextBox;

            string antT = tb.Text;

            string t = tb.Text;

            e.Handled = MyClase.OnlyNumbers(e.KeyChar.ToString(), true, ref t);

            if (antT != t)

            {

                tb.Text = t;

                tb.SelectionStart = tb.Text.Length;

            }

        }

 

        private void txtPt2X_KeyPress(object sender, KeyPressEventArgs e)

        {

            TextBox tb = sender as TextBox;

            string antT = tb.Text;

            string t = tb.Text;

            e.Handled = MyClase.OnlyNumbers(e.KeyChar.ToString(), true, ref t);

            if (antT != t)

            {

                tb.Text = t;

                tb.SelectionStart = tb.Text.Length;

            }

        }

 

        private void txtPt2Y_KeyPress(object sender, KeyPressEventArgs e)

        {

            TextBox tb = sender as TextBox;

            string antT = tb.Text;

            string t = tb.Text;

            e.Handled = MyClase.OnlyNumbers(e.KeyChar.ToString(), true, ref t);

            if (antT != t)

            {

                tb.Text = t;

                tb.SelectionStart = tb.Text.Length;

            }

        }

 

        private void txtPt2Z_KeyPress(object sender, KeyPressEventArgs e)

        {

            TextBox tb = sender as TextBox;

            string antT = tb.Text;

            string t = tb.Text;

            e.Handled = MyClase.OnlyNumbers(e.KeyChar.ToString(), true, ref t);

            if (antT != t)

            {

                tb.Text = t;

                tb.SelectionStart = tb.Text.Length;

            }

        }

 

        private void txtPtX_KeyPress(object sender, KeyPressEventArgs e)

        {

            TextBox tb = sender as TextBox;

            string antT = tb.Text;

            string t = tb.Text;

            e.Handled = MyClase.OnlyNumbers(e.KeyChar.ToString(), true, ref t);

            if (antT != t)

            {

                tb.Text = t;

                tb.SelectionStart = tb.Text.Length;

            }

        }

 

        private void txtPtY_KeyPress(object sender, KeyPressEventArgs e)

        {

            TextBox tb = sender as TextBox;

            string antT = tb.Text;

            string t = tb.Text;

            e.Handled = MyClase.OnlyNumbers(e.KeyChar.ToString(), true, ref t);

            if (antT != t)

            {

                tb.Text = t;

                tb.SelectionStart = tb.Text.Length;

            }

        }

 

        private void txtPtZ_KeyPress(object sender, KeyPressEventArgs e)

        {

            TextBox tb = sender as TextBox;

            string antT = tb.Text;

            string t = tb.Text;

            e.Handled = MyClase.OnlyNumbers(e.KeyChar.ToString(), true, ref t);

            if (antT != t)

            {

                tb.Text = t;

                tb.SelectionStart = tb.Text.Length;

            }

        }

 

        private void txtPrecision_KeyPress(object sender, KeyPressEventArgs e)

        {

            TextBox tb = sender as TextBox;

            string antT = tb.Text;

            string t = tb.Text;

            e.Handled = MyClase.OnlyNumbers(e.KeyChar.ToString(), false, ref t);

            if (antT != t)

            {

                tb.Text = t;

                tb.SelectionStart = tb.Text.Length;

            }

        }

 

        private void btCalcular_Click(object sender, EventArgs e)

        {

            this.lblMsg.Text = “Mensaje:”;

            // Verificar los valores en los TextBox

            if (!MyClase.IsNumeric(this.txtPt1X.Text) ||

                !MyClase.IsNumeric(this.txtPt1Y.Text) ||

                !MyClase.IsNumeric(this.txtPt1Z.Text) ||

                !MyClase.IsNumeric(this.txtPt2X.Text) ||

                !MyClase.IsNumeric(this.txtPt2Y.Text) ||

                !MyClase.IsNumeric(this.txtPt2Z.Text) ||

                !MyClase.IsNumeric(this.txtPtX.Text) ||

                !MyClase.IsNumeric(this.txtPtY.Text) ||

                !MyClase.IsNumeric(this.txtPtZ.Text) ||

                !MyClase.IsNumeric(this.txtPrecision.Text))

            {

                this.lblMsg.Text = “Mensaje: Formato erróneo en los números o en la precisión.”;

            }

            Point3D StartPoint = new Point3D(this.txtPt1X.ToDouble(), this.txtPt1Y.ToDouble(), this.txtPt1Z.ToDouble());

            Point3D EndPoint = new Point3D(this.txtPt2X.ToDouble(), this.txtPt2Y.ToDouble(), this.txtPt2Z.ToDouble());

            Point3D RefPoint = new Point3D(this.txtPtX.ToDouble(), this.txtPtY.ToDouble(), this.txtPtZ.ToDouble());

            double precision = this.txtPrecision.ToInteger();

            if (MyClase.PointInLine(RefPoint,StartPoint,EndPoint, Convert.ToInt16(precision)))

            {

                this.lblMsg.Text = “Mensaje: El punto SI está en el segmento.”;

            }

            else

            {

                this.lblMsg.Text = “Mensaje: El punto NO está en el segmento.”;

            }

        }

Cuando lo ejecutes el resultado debería ser parecido al siguiente:

Ponlo a prueba, piensa en cómo mejorarlo y comparte con nosotros tus progresos.

Deja un comentario

Tu dirección de correo electrónico no será publicada.

Información básica sobre protección de datos Ver más

  • Responsable: MTB Software de Ponent, SLU.
  • Finalidad:  Moderar los comentarios.
  • Legitimación:  Por consentimiento del interesado.
  • Destinatarios y encargados de tratamiento:  No se ceden o comunican datos a terceros para prestar este servicio. El Titular ha contratado los servicios de alojamiento web a Hostinet, SL que actúa como encargado de tratamiento.
  • Derechos: Acceder, rectificar y suprimir los datos.
  • Información Adicional: Puede consultar la información detallada en la Política de Privacidad.

Esta web utiliza cookies propias y de terceros para su correcto funcionamiento y para fines analíticos. Al hacer clic en el botón Aceptar, acepta el uso de estas tecnologías y el procesamiento de tus datos para estos propósitos. Ver Política de cookies
Privacidad