Fold each faces to create a cube

Hi, everyone. I have a problem right now. What i wanna do is to draw 6 faces of a cube on the plane of y=0 first, and then by clicking a button, all faces will fold to create a cube.

I have drawn all faces, but for folding, i cannot figure out. Note that in the function of drawing faces, i use a variable to determine which side of the face is used to rotate about.

Here is the problem. i cannot rotate top and right faces correctly, because their rotating line is moving, i.e. the lines rotate with other faces. Are there any hints for me?