Other
Rotate a Vector2 around the Z axis on a mathematical level
This is what i want to achieve with a givin Vector2 and a float degree i want to get the new ("rotated") Vector2, if this makes anysense at all.
Answer by Bunny83 · Aug 15, 2016 at 04:04 PM
Well all you need is a "2x2 rotation matrix". This can be easily calculate manually like this:
Vector2 Rotate(Vector2 aPoint, float aDegree)
{
float rad = aDegree * Mathf.Deg2Rad;
float s = Mathf.Sin(a);
float c = Mathf.Cos(a);
return new Vector2(
aPoint.x * c - aPoint.y * s,
aPoint.y * c + aPoint.x * s;
);
}
This should rotate the point counter clockwise around the origin. If you wan to rotate clockwise you can either use a negative angle or flip the signs of the "sin" component
return new Vector2(
aPoint.x * c + aPoint.y * s,
aPoint.y * c - aPoint.x * s;
);
ps: I've written this from scratch without syntax checking. However it should work that way.
edit
If you want to rotate around a certain point you could do:
Vector2 RotateAroundPivot(Vector2 aPoint, Vector3 aPivot, float aDegree)
{
aPoint -= aPivot;
float rad = aDegree * Mathf.Deg2Rad;
float s = Mathf.Sin(a);
float c = Mathf.Cos(a);
return aPivot + new Vector2(
aPoint.x * c - aPoint.y * s,
aPoint.y * c + aPoint.x * s;
);
}
Another way would be to use a Quaternion (or the 2d equivalent: complex numbers). See this vid for an introduction into complex numbers and quaternions.
So you can simply do:
Vector2 Rotate(Vector2 aPoint, aDegree)
{
return Quaternion.Euler(0,0,aDegree) * aPoint;
}
Or with an extension class like this:
public static class ComplexEx
{
public static Vector2 Complex$$anonymous$$ult(this Vector2 aVec, Vector2 aOther)
{
return new Vector2(aVec.x*aOther.x - aVec.y*aOther.y, aVec.x*aOther.y + aVec.y * aOther.x);
}
public static Vector2 Rotation(float aDegree)
{
float a = aDegree * $$anonymous$$athf.Deg2Rad;
return new Vector2($$anonymous$$athf.Cos(a), $$anonymous$$athf.Sin(a));
}
public static Vector2 Rotate(this Vector2 aVec, float aDegree)
{
return Complex$$anonymous$$ult(aVec, Rotation(aDegree));
}
}
With that class you can rotate any Vector2 like this:
Vector2 rotated = vec.Rotate(20f); // rotate "vec" by 20° counter clockwise.
Again, all written from scratch and not tested ^^-