When can you use cos and sin outside of setup or draw

Is there any instances where you can do this. So far I understand that you can create a function outside of setup or draw which contain cos or sin, but they have to be called in draw or setup to work or it will give you an error. Also wanted to check if there is any way around this.

Thanks.

1 Like

All Processing’s (PApplet) static members can be accessed from anywhere: :cloud_with_lightning:

Not sure what you mean by PAplet, (fairly new to programming). I’m currently using p5.js, I would assume perhaps wrongly that processing uses the same logical structure. But just to clarify so far I haven’t been able to use sin, cos, outside of setup or draw, other functions such as round or random are also unavailable.

Please note that it doesnt not mean that they can’t be written outside of setup or draw, but they have to be processed through setup or draw.

ie

this will not work;


var a = cos(60)*100;
var b;
function setup(){

function someFunction(){

b = a*200;
}
}

nor this;

var b;
function setup(){

function someFunction(){

var a = cos(60)*100;
return a;
}
}

var b  = someFunction();

function draw(){
};

However this will work;

var b;
function setup(){

}

function someFunction(){

var a = cos(60)*100;
b = a*200;

return b;
}

function draw(){
var a = someFunction();
};

and this will work;

var b;
function setup(){

function someFunction(){

var a = cos(60)*100;
return a;
}
}

function draw(){
var b  = someFunction();
};
1 Like

I’ve changed your post to the p5.js forum category then. :expressionless:

p5js is a diff. flavor beast. :bear:

Indeed, none of its API is available until either it finds out that setup() or draw() is in the global context (window) or we manually instantiate class p5: new p5; :cowboy_hat_face:

new p5; // prematurely instantiate class p5. ;-)

const SQRT_3 = sqrt(3); // we can access p5's sqrt() method outside functions!

function setup() {
	print(SQRT_3);
}

For cos() & sin() and similar, we can always directly rely on the class Math: :bulb:

const SQRT_3 = Math.sqrt(3); // Directly accessing JS' Math method sqrt().

function setup() {
	print(SQRT_3);
}
1 Like

Ah ok, thanks for taking the time to answer.