Help with 3d rotation

So I’m trying to make all the objects in a 3d world rotate on the z axis, depending on the rotate of the z axis in the iPad.
I’ve got it to work a little bit, but it’s not good. When I tilt too far the object flys off view. I tried debugging it using “print()” and found out that the y position was being changed by a ton for some reason. I’ll post code

    pushMatrix() 
    setContext(screen)
    perspective(FieldOfView,WIDTH/HEIGHT)
    background(0, 0, 0, 0)
    angle = angle + RotationRate.y / math.abs(Gravity.y/2)
    x, y, z = math.sin(math.rad(angle)), Gravity.z , math.cos(math.rad(angle))
    rotate_degree = (rotate_degree + RotationRate.z / math.abs(Gravity.z/2))
    camera(0, 0, 0,x, y, z, 0, 1, 0)
    rectMode(CENTER)
    
    pushStyle()
    translate(0, 0, 100)
    rotate(-rotate_degree,0,0,1)
    stroke(0, 2, 255, 255)
    rect(0,0,5,5)
    popStyle()
    
    rotate(rotate_degree,0,0,1)
    
    pushStyle()
    translate(0,-50,0)
    rotate(-rotate_degree,0,0,1)
    stroke(14, 255, 0, 255)
    rect(0,0,5,5)
    popStyle()
    
    rotate(rotate_degree,0,0,1)
    
    pushStyle()
    translate(25,25,0)
    rotate(45,0,1,0)
    rotate(-rotate_degree,0,0,1)
    stroke(255, 0, 3, 255)
    rect(0,0,5,5)
    popStyle()
    
    rotate(rotate_degree,0,0,1)

So I’m still learning how 3d works. So I know that the rotate part of code is not good. But can anyone help me with this?

@Leviathan - it could be because each translation is being added to the one before, and each time you draw, it keeps adding.

If you want each translation to be separate, you need to put pushMatrix() before each translation and popMatrix() after the translation (like you have done with pushStyle).

Alright, thank you. I’ll try that out.