0
\$\begingroup\$

I have a list of points that I want to rotate around the origin by 90, 180 or 270 degrees. This list can be an arbitrary shape such as:

// # # #
// #
// * # #

// The * Represents the origin
int rotation = 0; 
List<Vector2Int> points; 

How would I rotate the values of the points to get a new set of points where it's rotated around the origin.

rotation = 1; // 90 degrees
// * # #
// #   #
// #   #
rotation = 2; // 180 degrees
// # # *
//     #
// # # #
rotation = 3; // 270 degrees
// #   #
// #   #
// # # *

I can get them by flipping the values of x and y and setting x or y to negative but I feel there's an easier way to do this that I can't think of.

public List<Vector2Int> rotatePoints(List<Vector2> originalList, int rotation){
    List<Vector2Int> newList = new List<Vector2Int>();
    //foreach point in originalList
    if(rotation == 1){
        // 90 degrees
        newPoint = new Vector2Int(oldPoint.y, -oldPoint.x);
    } else if(rotation == 2){
        // 180 degrees
        newPoint = new Vector2Int(-oldPoint.x, -oldPoint.y);
    } else if(rotation == 3){
        // 270 degrees
        newPoint = new Vector2Int(-oldPoint.y, oldPoint.x);
    } else {
        // 360 or 0 degrees
        newPoint = oldPoint;
    }


    //set the points to a new list and return that list
    return newList;
}

Is there any easier way to do this?

\$\endgroup\$
  • 1
    \$\begingroup\$ The flipping method is the faster one. It's basically the sin/cosine method simplified \$\endgroup\$ – Bálint Aug 11 '18 at 20:59

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.