We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello,
I'm currently reading The Nature of Code and I noticed that in some of the examples PVector is defined in draw. Take Example 1.4:
void setup() {
size(640,360);
}
void draw() {
background(255);
PVector mouse = new PVector(mouseX,mouseY);
PVector center = new PVector(width/2,height/2);
mouse.sub(center);
//Multiplying a vector! The vector is now half its original size (multiplied by 0.5).
mouse.mult(0.5);
translate(width/2,height/2);
line(0,0,mouse.x,mouse.y);
}
I've been using Processing for a while but I'm not a Java expert. I was wondering if the compiler does something to save the PVector because it seems like declaring new ones in each draw frame would be really inefficient.
Generally I layout my sketches like this:
MyObject myObject;
PVector myPVector;
void setup() {
myObject = new myObject();
myPVector = new PVector();
}
void draw() {
myObject.update();
myPVector.update();
}
In general, is it costly to define objects in draw? I know that I gained a lot of speed in an Android game I made just by replacing ArrayLists with arrays of game objects so I figured it would be.
Answers
It will be more efficient to create the objects in setup and update them in draw, if needed. In your example the PVector
center
will only change if the sketch window is resized, so won't need changing if the window is not resizable.P.S.: Though an excellent book for computer drawings, it's the worst example for efficiency techniques! :P