ofRectangle doesn't rotate properly when translating the coordinate system at every frame

Hi everyone, I’m experimenting with OfxOpenNI + Nite.
The context is as follows: I want to rotate a simple 2D rectangle with the body movement: ie, if the person moves to the right then a 90º clock wise rotation happens. The movement is driven by the y_cm body center of mass. Thus: y_rect = f(y_cm).

I’ve been reading similar topics to this one but no one gave me some light to my problem.

Approach:
I had to did some tricks to enlarge the x coordinates gap difference between two frames to avoid an excessive responsiveness.
I considered more than one frame to get the previous and actual x coordinate by acumulating the time between frames by using ofGetLastFrameTime(). If the sum of the time is greater than certain threshold then I check the differences between the previous and the actual coordinate.
I don’t know if this approach is the best, it could be improved by far, I am open to your suggestions.

Code:

void testApp::update()
{
    openNIDevice.update();


    
    if (y_rec > y_tope)
    {
        y_rec = 15;
        w = 40;
        h = 82;
    }

    if (t < 1.0)
    {
        t += ofGetLastFrameTime();
    }
    else
    {
        t = 0;
        x_ant = x;
    }
:::::::::::::::::::::::::::::::::::

x_ant is the previous x coordinate

x1 and x2 are the physical boundaries to avoid the easy responsiveness of every body movement.

void testApp::draw()
    ofPushMatrix();
    ofSetRectMode(OF_RECTMODE_CORNER);
    ofSetColor(255, 128, 0);
    ofFill();
    ofTranslate(x_rec,y_rec,0);

    if (((x <= x2) || ((x - x1) > 15)) && (t >= 1.0))// mueve hacia la derecha de x1
    {
        if ((x - x_ant) > 27)
        {
            ofRotateZ(90);
            ofRect(-w/2,-h/2,w,h); // para que escriba en torno a 0,0
         
//            if (w == 40)   **USING THE COMMENTED LINES WORKS FINE**
//            {
//                h = 40;
//                w = 82;
//            }
//            else
//            {
//                h = 82;
//                w = 40;
//            }
//        }
      }
   }
   else
    ofRect(-w/2,-h/2,w,h);

   ofTranslate(-x_rec,-y_rec,0);
   ofPopMatrix();

Troubles:
The rectangle rotates but it go back inmediately to the original position when it sould remain until the next body movement instead.
If I do it without using the ofRotateZ or ofRotate(90, 0,0,1) and ofTranslatio but with the code commented, it works fine.
What’s wrong in this approach? I guess it has to do with the coordinate translations at every frame.

Thanks!