This year on 254 we switched to using a simple Rotation2d class for all angles (because, among other reasons, dealing with angle rollover as you did here is easy to screw up). Internally, this class stores the sine and cosine of an angle explicitly. This has some nice properties:
- We use static utility methods to create a Rotation2d from a vector (x,y -> cos,sin after normalization), absolute angle in radians, or absolute angle in degrees.
- We have accessors that return the absolute angle in degrees or radians (wrapped to -Pi to Pi).
- We have "Inverse()" and "RotateBy(Rotation2d other)" methods for creating a new Rotation2d:
Code:
Rotation2d Inverse() {
return new Rotation2d(cos_angle, -sin_angle);
}
Rotation2d RotateBy(Rotation2d other) {
return new Rotation2d(cos_angle * other.cos_angle - sin_angle * other.sin_angle,
cos_angle * other.sin_angle + sin_angle * other.cos_angle);
}
- If you want to know the shortest rotation from A to B, you can do something like:
Code:
double shortest_distance_degrees = A.Inverse().RotateBy(B).ToDegrees();
This will always give you a solution on [-180, 180]. - Cheap access to the sine, cosine, and tangent (sin/cos) of the angle because they are already cached.