Now you now know how to call functions, use variables, and create your own variables.
This is a companion discussion topic for the original entry at https://happycoding.io/tutorials/processing/creating-functions
Now you now know how to call functions, use variables, and create your own variables.
I was trying to use the translate(x,y) function and it was behaving weirdly when placed inside a custom (user-defined) function of mine. It worked as expected only when I placed it inside the draw() function. Why does this happen? Do I need to always use it inside the draw() function only?
Hmm no, it shouldn’t matter if it’s inside draw()
or inside a function that you call from draw()
. Can you post some code that shows what you’re seeing?
class Star{
float x,y,z;
float sizeX,sizeY;
Star(){
x=random(-width/2,width/2);
y=random(-height/2,height/2);
sizeX=5;
sizeY=5;
}
void display(){
translate(width/2,height/2);
noStroke();
ellipse(x,y,sizeX,sizeY);
}
}
Star[] arrStars= new Star[1000];
void setup(){
size(600,600);
createStars();
background(0);
}
void draw(){
background(0);
//translate(width/2,height/2);
displayStars();
}
void createStars(){
for(int i=0;i<arrStars.length;i++)
arrStars[i]=new Star();
return;
}
void displayStars(){
//translate(width/2,height/2);
for(int i=0;i<arrStars.length;i++){
arrStars[i].display();
}
}
I think I got why this was happening.
Each time draw() is called, everything (like the translation of origin because of translate() functions) is reset.
But if in one iteration of draw() if I call the translate(x,y) function many times(say 10 times) then it adds up each translate(x,y) call and translates the origin by corresponding cumulated sum times(10x, 10y).
Yep, that’s exactly right.
To get around this, you might look into using the pushMatrix()
and popMatrix()
functions:
I tried using pushMatrix() and popMatrix(). It worked like magic.