Question

I have this:

static double[] RotateVector2d(double x, double y, double degrees)
{
    double[] result = new double[2];
    result[0] = x * Math.Cos(degrees) - y * Math.Sin(degrees);
    result[1] = x * Math.Sin(degrees) + y * Math.Cos(degrees);
    return result;
}

When I call

RotateVector2d(1.0, 0, 180.0)

the result is: [-0.59846006905785809, -0.80115263573383044]

What to do so that the result is [-1, 0] ?

What am I doing wrong?

Was it helpful?

Solution

The angle is measured in radians, not degrees. See http://msdn.microsoft.com/en-us/library/system.math.cos(v=vs.110).aspx

OTHER TIPS

A couple of things: Use Vector to represent vectors.

  • v.X reads better than v[0]
  • It is a struct so it will have nice performance.
  • Be aware that Vector is a mutable struct.

For rotation perhaps an extension method makes sense:

using System;
using System.Windows;

public static class VectorExt
{
    private const double DegToRad = Math.PI/180;

    public static Vector Rotate(this Vector v, double degrees)
    {
        return v.RotateRadians(degrees * DegToRad);
    }

    public static Vector RotateRadians(this Vector v, double radians)
    {
        var ca = Math.Cos(radians);
        var sa = Math.Sin(radians);
        return new Vector(ca*v.X - sa*v.Y, sa*v.X + ca*v.Y);
    }
}

Sin and Cos take values in radians, not degrees. 180 degrees is Math.PI radians.

Alternative if you want to use degrees without conversion using Matrix:

    System.Windows.Media.Matrix m = new System.Windows.Media.Matrix();
    m.Rotate((double)angle_degrees);
    System.Windows.Vector v = new System.Windows.Vector(x,y);
    v = System.Windows.Vector.Multiply(v, m);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top