NMD 105 Creative Coding I

P5js Pitfalls 2

"Green Brain99099" by Luis Ruiz

More

More pitfalls

New and old sketches

✅ Command-S in the code saves the sketch.

❌ Command-S elsewhere on the screen tries to save the entire web page to your desktop.

🐞 If your old code appears when you click the New Sketch button, try File > New.

Undoing and re-doing

✅ Command-Z should undo changes.

✅ Command-Y should redo changes.

🐞 Control-Z doesn't always undo. Worried about ruining your code? Duplicate the sketch.

🐞 Disable autorefresh when writing a loop, or you could get caught in an infinite refresh.

Placing p5js code

⚠ī¸ Put your paint layers in the right order! If you make a small shake and then on the next line make a big shape, the big shape will cover the small shape.

⚠ī¸ Don't put the background() in your function.

⚠ī¸ If you have transforms, wrap them in push/pop inside your function.

⚠ī¸ Don't put background() in a function called from draw().

ℹī¸ To comment more than one line of code, use /* ... */

Computer math

🤷 Computer scientists count from zero.

⚠ī¸ You won't be able to see collinear shapes, eg triangle(100,100,200,200,300,300). Add a stroke!

⚠ī¸ Unlike high school math, the Y axis points down from the top of the canvas.

Animation glitches

If your sketch is acting erratically, eg target moves faster after projectile launches:

🛠 Check your placement of push() and pop(). Is the latter missing?

🛠 You could have redundant code for positioning so it goes twice as fast and far, eg:


	    translate(x, y);
	    ellipse(x, y, 100)

⚠ī¸ x and y are additive and subtractive, but scale() takes a ratio, eg:


// This will move the rectangle 2 pixels to the right.
translateX( 2 )
rect( ... );

// This will double the size of the rectangle.
scale( 2 )
rect( ... );

Sharing code

✅ Always save your sketch before sharing the URL.

⚠ī¸ If you have transforms, wrap them in push/pop inside your function.

⚠ī¸ When adding another person's code, watch out for conflicting settings like angleMode, rectMode.

/