Home > Mobile >  Rotation of square by center using rotation matrix
Rotation of square by center using rotation matrix

Time:05-17

I'm trying to rotate a square using rotation matrix with this implementation.

void Square::rotateVertices(std::vector<float> &vertices)
{
   float px = (vertices[0] vertices[2])/2;
   float py = (vertices[1] vertices[5])/2;        
   for (int i = 0; i < 4; i  )
   {
       float x1 = vertices[i*2];
       float y1 = vertices[i*2 1];
       vertices[i * 2] = px   (x1 -px)*cos(angle) - (y1 -py)*sin(angle);
       vertices[(i * 2)   1] = py   (x1 -px)*sin(angle)   (y1 -py)*cos(angle);
    }
}

Vertices are calculated using code below:

float ay = (size / float(height) / 2.f), ax = (size / float(width) / 2.f);
std::vector<float> vertices = {
            2 * (((x) - float(width) / 2) / float(width)) - ax, 2 * ((y - float(height)) / float(height)) - ay   1.0f,
            2 * (((x) - float(width) / 2) / float(width))   ax, 2 * ((y - float(height)) / float(height)) - ay   1.0f,
            2 * (((x) - float(width) / 2) / float(width))   ax, 2 * ((y - float(height)) / float(height))   ay   1.0f,
            2 * (((x) - float(width) / 2) / float(width)) - ax, 2 * ((y - float(height)) / float(height))   ay   1.0f};
rotateVertices(vertices);

where:

  • width - window width
  • height - window height
  • size - size of square

After calculation square looks normal for angle=0, but when I've checked ie. angle=M_PI/4 which should rotate square 45 degrees, rotation applies with strange transformation of square to rectangle.(as shown in pictures) Squares rotation example

Of course I would love to have the proportions kept, but I cannot think of the solution at the moment. If anybody could think of fast fix, or could point me in the correct direction I would be pleased.

CodePudding user response:

That's because your square is a rectangle. My crystal ball knows this because its width and height are calculated separately, and therefore, you meant for them to be different:

// if you wanted these to be the same you wouldn't calculate them separately
float ay = (size / float(height) / 2.f), ax = (size / float(width) / 2.f);

The only reason it looks like a square is because the screen projection is also distorted to cancel it out.

When you rotate the rectangle they no longer cancel out.

You should draw a square with the same width and height, and then fix the matrices that convert the square into screen coordinates, so that when you render something with the same width and height it does get the same width and height on the screen.

  • Related