Obtener un punto a una distancia y un ángulo respecto a otro punto

Vamos a presentar dos minúsculas funciones que te servirán para obtener un punto respecto a otro en función de la distancia y el ángulo. Como ya venimos comentando en posts anteriores los ángulos se cuentan en radianes, en sentido trigonométrico (antihorario) y comienza a contar desde el “Este” (a la derecha del plano).

En las funciones manejaremos la clase Point3D que ya comentamos en otro post.

Veamos la función:

        /// <summary>

        /// Obtiene un punto polar 3D

        /// </summary>

        /// <param name=”pt“>Punto 3D de referencia</param>

        /// <param name=”ang“>Ángulo sobre el eje X (radianes)</param>

        /// <param name=”dist“>Distancia</param>

        /// <returns></returns>

        public static Point3D PolarPoint(Point3D pt, double ang, double dist)

        {

            return new Point3D(pt.x + dist * Math.Cos(ang), pt.y + dist * Math.Sin(ang), pt.z);

        }

Para ponerlo a prueba puedes crearte un pequeño 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 txtDistancia_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 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

            // Si recibimos MinValue significa que no hay valor válido.

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

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

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

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

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

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

            {

                this.lblResult.Text = “”;

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

            }

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

            double distancia = this.txtDistancia.ToDouble();

            double angulo = MyClase.d2r(this.txtAngulo.ToDouble());

            int precision = this.txtPrecision.ToInteger();

            // Por si al usuario se le ha ocurrido poner algún ángulo superior a 360

            while (angulo >= Math.PI * 2)

            {

                angulo -= Math.PI * 2;

            }

            Point3D destino = MyClase.PolarPoint(origen, angulo, distancia);

            double newX = MyClase.Trunk(destino.x, Convert.ToInt16(precision));

            double newY = MyClase.Trunk(destino.y, Convert.ToInt16(precision));

            double newZ = MyClase.Trunk(destino.z, Convert.ToInt16(precision));

            this.lblResult.Text = newX.ToString() + “;” + newY.ToString() + “;” + newZ.ToString();

        }

El resultado final 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