One Small Trick about Transformation in Processing

Rodger Luo
3 min readJan 29, 2018

--

This article assumes the readers have basic knowledge of Processing.

Rotating a cube at the center of the canvas

The concept of 2D transformation is somewhat confusing for beginners of Processing, especially about self-rotation. Self-rotation means an object rotates around its own z-axis. In Processing, implementing self-rotation is not straightforward as implementing translation or scale.

On the Processing official website, it gives an example demonstrating how to rotate a square around its center (https://processing.org/examples/rotate.html), but doesn’t explicitly explain the method used for self-rotation. This article tries to generalize the self-rotation method in 2D transformation.

The default rotate function was not designed for self-rotation, as the function rotates objects around the origin of the coordinate system. By default, the origin is at the upper-left vertex of the canvas, so only applying the rotate function would result in objects rotate around the z-axis through the upper-left vertex rather than rotate around their own z-axes.

One common solution is to translate the origin to the center of the canvas. In the Processing example, it translates the coordinate system by applying translate(width/2, height/2), then apply x and y parameter of the square to (0, 0) which is at the center of the canvas after the translation.

The follow-up question is how to make the square self-rotate at different locations. One intuitive answer is to change x and y parameter in rect function based on the translated coordinate system. For example, x = width/4 and y = height/4 should make the square self-rotate at the center of the lower right sub-square if we evenly divide the square into four sub-squares. However, the result is unexpected. It doesn’t work because rotate function always rotates objects around the origin of the coordinate system.

Therefore, a good method for rotating an object around its own axis is to make the origin of the coordinate system always at the center of the object. The steps are as follows: 1) translating the origin of the coordinate system to the center of the canvas, 2) always keeping the x and y parameter in rect function as (0, 0), 3) applying the position (x and y parameter) in the translate function which translates the coordinate system. The following codes demonstrate how to make a square self-rotate 90 degrees at the center of the upper left sub-square.

float x_pos = -width/4;
float y_pos = -height/4;
translate(width/2+x_pos, height/2 +y_pos);
rotate(PI/2);
rect(0, 0, 180, 180);

In fact, this method is commonly used for 3D transformation in Processing, but it is not well explained in 2D transformation.

--

--

Rodger Luo

Lecturer & Ph.D. candidate at Media Arts & Technology, UC Santa Barbara