[英]How to rotate 2d vector?
我有这个:
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;
}
当我打电话
RotateVector2d(1.0, 0, 180.0)
结果是: [-0.59846006905785809, -0.80115263573383044]
怎么做才能使结果为[-1, 0]
?
我究竟做错了什么?
有两件事:使用Vector
表示向量。
Vector
是可变结构。 对于旋转,也许可以使用扩展方法:
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
和Cos
以弧度而不是度为单位。 180度是Math.PI
弧度。
如果要使用度数而不使用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.