[Nature of Code] P5.js quick references
Nature of Code note series
Basics: setup(), draw()
All P5.js builtin functions and variables are available in the setup()
and draw()
functions. It doesn’t work if you reference them outside without instance mode.
Instance mode:
const p5 = new p5();
console.log(p5.PI);
translate, push and pop
translate(vec)
moves the current reference frame by a vector vec
, so that the new (0, 0)
is the old (vec.x, vec.y)
.
push()
means to save the current reference frame, pop()
is to restore back to the previous reference frame.
Mouse and keyboard interactions
mousePressed()
, mouseDragged()
, etc.
Sound
Small example (matter.js collision):
let ding;
function preload() {
ding = loadSound('/assets/vibraphone-ding.mp3');
}
function collideSound(event) {
const pairs = event.pairs;
for (const pair of pairs) {
const labelA = pair.bodyA.label;
const labelB = pair.bodyB.label;
if (labelA === 'ground' && labelB === 'particle') {
ding.play();
}
}
}
function setup() {
...
Events.on(engine, 'collisionEnd', collideSound);
}