Reputation: 2956
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?
Upvotes: 16
Views: 59778
Reputation: 133
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);
Upvotes: 1
Reputation: 17580
A couple of things:
Use Vector
to represent vectors.
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);
}
}
Upvotes: 25
Reputation: 31393
Sin
and Cos
take values in radians, not degrees. 180 degrees is Math.PI
radians.
Upvotes: 5
Reputation: 1804
The angle is measured in radians, not degrees. See http://msdn.microsoft.com/en-us/library/system.math.cos(v=vs.110).aspx
Upvotes: 26