Skip to content
Advertisement

How to roll up a 2D Grid in P3D with Processing

I have built a two-dimensional grid of rectangles with a nested loop. Now I want to “roll up” this grid in three-dimensional space, or in other words “form a cylinder” or a “column”. With the movement of my mouse pointer. Up to the “roll up” I get everything programmed as desired – but then my mathematics fails.

JavaScript

Instead of a roll up, the grid twists twice…. I thought I could achieve the “roll up” by concatenating sin(); and cos(); – similar to this example:

JavaScript

What is the best way to achieve this roll up?

Advertisement

Answer

You are on the right track using the polar to cartesian coordinate system transformation formula.

There are multiple ways to solve this. Here’s an idea, starting in 2D first: unrolling a circle to a line. I don’t know the 100% mathematically correct way of doing this and I hope someone else posts this. I can however post a hopepfully convincing enough estimation using these “ingredients”:

  • The length of the circle (circumference) is 2πR
  • Processing’s lerp() linearly interpolates between two values (first two arguments of the function) by a percentage (expressed a value between 0.0 and 1.0 (called a normalized value) -> 0 = 0% = start value, 0.5 = 50% = half-way between stard and end value, 1.0 = 100% = at end value)
  • Processing provides a PVector class which is both handy to encapsulate 2D/3D point properties (.x, .y, .z), but also provides a lerp() method which is a nice shorthand to avoid manually lerping 3 times (once for each dimension (x, y, z))

Here’s a basic commented sketch to illustrate the above:

JavaScript

24 points on a circle that linearly interpolate to a line using the mouse X position

The same logic can be applied in 3D with an extra loop to repeat circles/lines to appear as a cylinder/grid:

JavaScript

multiple circles stacked in 3D appear a cylinder that unrolls to a plane when the mouse X position moves left to right

The above code would’ve worked without PVector, but it would be more verbose. The other thing to keep in mind is that a the static PVector.lerp() method will generate a new PVector instance per call: this is ok for small demo such as this, but caching a bunch of PVectors to lerp() should waste less memory.

For the sake of completeness here are interactive versions your can run right here via p5.js:

JavaScript
JavaScript

JavaScript
JavaScript

Update

As previously mentioned, you can work without PVector in this simple case:

JavaScript

Personally, I find the PVector version slightly more readable.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement