简体   繁体   中英

Use p5.js functions inside global variables

I want to have a file with global variables, for example:

function Globals() {

}

Globals.gravity = createVector(0, -9.81);

Unfortunately p5.js functions can only be used when they are declared inside setup() or draw() or are called from one of these functions.

My question is what would be the best approach to make globals easy to use?

My only idea is to make them functions, but that is not very pretty (you have to call function to get a value) and it is probably slow, because each access to a global variable requires making a call. Globals.gravity = function() { return createVector(0, -9.81); }

Well, fortunately, you could use p5.js functions outside setup() and draw() function.

In order to use those functions, you need to call new p5() beforehand, like so ...

new p5(); //<-- call this

function Globals() {}
Globals.gravity = createVector(0, -9.81);

For more info, refer here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM