[英]How to rotate 2d vector?
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]
结果是:
[-0.59846006905785809, -0.80115263573383044]
What to do so that the result is [-1, 0]
? 怎么做才能使结果为
[-1, 0]
?
What am I doing wrong? 我究竟做错了什么?
The angle is measured in radians, not degrees. 角度以弧度而不是度为单位。 See http://msdn.microsoft.com/en-us/library/system.math.cos(v=vs.110).aspx
参见http://msdn.microsoft.com/zh-cn/library/system.math.cos(v=vs.110).aspx
A couple of things: Use Vector
to represent vectors. 有两件事:使用
Vector
表示向量。
Vector
is a mutable struct. Vector
是可变结构。 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. Sin
和Cos
以弧度而不是度为单位。 180 degrees is Math.PI
radians. 180度是
Math.PI
弧度。
Alternative if you want to use degrees without conversion using Matrix: 如果要使用度数而不使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.