P5.js Plugin Documentation
Description:
Beginner friendly procedural rendering library
The P5 plugin allows entities to render themselves with two primary methods: 1. property based rendering 2. the .render() property
Property Based Rendering
The P5 plugin has support for rendering certain p5.js shapes by using a combination of properties on your Entity object. For example in our pong demo we draw our ball onto the screen using the following code:
Entity({
shape: "ellipse",
matter: {
shape: "circle",
friction: 0,
restitution: 1,
frictionAir: 0,
//mass: 1,
inertia: Infinity,
},
x: 0,
y: 0,
width: 2.5,
height: 2.5,
fill: "white",
})
There are a few things to note here. Firstly, our p5.js shape is automatically being drawn to the position on screen defined by it’s x, y, width, and height properties. Secondly, our ball has actual physics because we gave it a matterjs hitbox shape. So whenever matter updates our ball’s position in the world p5.js will automatically draw it to it’s new location. Basically matter.js and p5.js are coordinating their updates together perfectly without us having to do any work.
Also, we define the other p5.js specific properties on the Entity object as well, like the fill color, the stroke settings, and more. Here are the p5.js properties currently supported:
| Property Name | Valid Values | Description |
|---|---|---|
| .shape | “rectangle”, “ellipse” | the p5.js shape to use when drawing |
| .fill | any valid p5.js color value | the color to fill the p5.js shape |
| .stroke | any valid p5.js color value | the color to fill the p5.js stroke |
| .strokeWeight | any valid p5.js stroke size | the size of the p5.js stroke |
| .renderPriority | any finite number | set the draw order (higher = 1st) |
The .render Property
The P5 plugin doesn’t directly implement all of the functionality available in the p5.js library. That’s not to say you can’t do it, but sometimes you gotta do it yourself. When we assign a .render property to an Entity the p5.js plugin will automatically call that function with the p5.js instance as the first argument and your entity’s position data as the second argument (because the p5.js renderer doesn’t know about our virtual coordinate system). Note that we must prepend “p.” to all of our p5.js calls because we aren’t using it in global mode. Here’s an example of me using the render method to display text in the Pong game using p5.js because the p5.js plugin doesn’t currently have property based text rendering support:
const player1ScoreDisplay = entities.addChild(
Entity({
fill: infoColor,
render: (p, positionData) => {
const { x, y } = positionData;
p.textSize(p.width / 10);
p.textAlign(p.CENTER);
p.text(player1Score.get(), x, y);
},
x: -25,
y: -40,
renderPriority: -10,
}),
);
Learn more about p5.js
For further questions about how p5.js works please see the p5.js website.
