Can’t use math functions inside class constructor, and some other functions like print(“Hi”) for example.
I don’t mind, but it kinda makes my code look ugly having to use JavaScript Math.random() for example. Which has different behavior too.
The following is modified from the p5.js Objects > ex01_Objects example. Note that it successfully calls functions from within the constructor.
/*
* @name Objects
* @description Create a Jitter class, instantiate an object,
* and move it around the screen. Adapted from Getting Started with
* Processing by Casey Reas and Ben Fry.
*/
let bug; // Declare object
function setup() {
createCanvas(710, 400);
// Create object
bug = new Jitter();
}
function draw() {
background(50, 89, 100);
bug.move();
bug.display();
}
// Jitter class
class Jitter {
constructor() {
this.x = random(width);
this.y = random(height);
this.diameter = random(10, 30);
this.speed = 1;
/****** @javagar added function calls inside constructor ******/
print("Hello, I'm your new Jitter!!");
print("My area is " + PI * pow(this.diameter / 2, 2));
}
move() {
this.x += random(-this.speed, this.speed);
this.y += random(-this.speed, this.speed);
}
display() {
ellipse(this.x, this.y, this.diameter, this.diameter);
}
}
Output:
Hello, I'm your new Jitter!!
My area is 88.54418682503436
You will encounter issues if you try to use global p5.js function statically before your setup()
function is called. For example, if the following were at the bottom of the code javagar shared it would not work:
// After declaring class Jitter
let notGoingToWork = new Jitter();
this is because the Jitter
constructor uses random
, width
, and print
which are not yet declared. Similarly using this functions directly at the top level of your file would not work either:
let alsoNotGoingToWork = random(10);
However if you absolutely must use p5.js functions statically before your setup()
function is called, some functions can be used directly on p5.prototype
:
let thisDoesWork = p5.prototype.random(10);
But be aware that that’s not going to work for all functions or properties. Some of them require the p5 instance to have already been created.
Okay, I understand. I can’t just type
let a=new Jitter();
function setup(){
…
}
It should be:
let a;
function setup(){
a=new Jitter();
}
My bad.
Maybe you can add a warning when people do that thing.