Matrix rotation but clockwise?

Hi,

I make a matrix rotation for my sand tetris, but my tetrominoes rotate counterclockwise.
I would like clockwise.

Here my code :

for(int i = 0; i < tileCellColorPosition.Count; i++)
        {
            int x =  tileCellColorPosition[i].Item2.x - data.xPointCenterTetro;
            int y =  tileCellColorPosition[i].Item2.y - data.yPointCenterTetro;

            Vector3Int newPoint = new Vector3Int(
                                              Mathf.RoundToInt(x * Mathf.Cos(Mathf.PI / 2) - y * Mathf.Sin(Mathf.PI / 2)),
                                              Mathf.RoundToInt(x * Mathf.Sin(Mathf.PI / 2) + y * Mathf.Cos(Mathf.PI / 2)));

            newPoint.x += data.xPointCenterTetro;
            newPoint.y += data.yPointCenterTetro;

            tileCellColorPosition[i] = new Tuple<int, Vector3Int>(tileCellColorPosition[i].Item1,  newPoint);
        }

Thank you !

I’ve removed the 2D-Physics tag as this post isn’t related to that and added a Tilemap tag although technically it’s not related to that either, it’s scripting/math.

Cos(a) / Sin(a) rotate counter-clockwise with positive angles as you use it so negative angles will do the opposite. Without changing too much you can use “-Mathf.PI / 2” or you can reformulate your use of Cos/Sin to be opposite.

Note: you’re being extremely wasteful here performing multiple repeated calls to get the same thing and then doing this in a loop. Performance will be awful and it all adds up. You should consider caching results. There are plenty of other improvements you could make here for speed too btw.

var rotateCW90 = -Mathf.PI / 2f;
var myCos90 = Mathf.Cos(rotateCW90);
var mySin90 = Mathf.Sin(rotateCW90);

for(int i = 0; i < tileCellColorPosition.Count; i++)
{
    int x =  tileCellColorPosition[i].Item2.x - data.xPointCenterTetro;
    int y =  tileCellColorPosition[i].Item2.y - data.yPointCenterTetro;

    Vector3Int newPoint = new Vector3Int(
                            Mathf.RoundToInt(x * myCos90 - y * mySin90),
                            Mathf.RoundToInt(x * mySin90 + y * myCos90));

    newPoint.x += data.xPointCenterTetro;
    newPoint.y += data.yPointCenterTetro;

    tileCellColorPosition[i] = new Tuple<int, Vector3Int>(tileCellColorPosition[i].Item1,  newPoint);
}
2 Likes

Thank you !

That’s works for me !

What do you mean by “you should consider caching results” ?

Thank you again !

I gave you an example. It’s caching the PI, Cos & Sin results. In your code you were calculating them again and again but they’re constants in that loop. Per-loop you are retrieving PI and dividing it by 2 four times and calculating Cos twice and Sin twice.

1 Like