We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › passing PVectors
Page Index Toggle Pages: 1
passing PVectors (Read 470 times)
passing PVectors
Aug 8th, 2009, 12:04pm
 
Hey quick question, but is there a specific way to pass PVectors to a function?

This sounds like a really easy question, but when I have code that essentially looks like this:

Code:

PVector vect1 = new PVector(2,2,2);

setup() {
 something here...
}

draw() {
 calc(vect1);
}

void calc(PVector v1) {
 v1.normalize();
}


I am having the problem that the passed global vector (in this case vect1) will be normalized! I do not want this to happen, is there a way to do this other than defining a new PVector, setting it to vect1, and then passing that PVector instead?

I had always thought that passing a variable will mean that the function would only get the value of the variable, not the actual variable itself
Re: passing PVectors
Reply #1 - Aug 8th, 2009, 2:34pm
 
If you pass a primitive type (int, float...), changing it won't change the original value.
Likewise, you cannot change the passed object (ie. if you do v1 = new PVector(), vect1 won't be changed) because that's just a reference (pointer) to some data structure, but the content of objects can be changed (the structure content).
So you guessed right, you have to copy the PVector if you don't want side effects.
Re: passing PVectors
Reply #2 - Aug 12th, 2009, 5:22am
 
PhiLho is correct (and arrays are also passed by reference not value). But note that PVector has a few static and other methods that do not affect the value of the input vector. For example you can get normalize() to create a new vector leaving the original intact:

Quote:
PVector vect1 = new PVector(2,2,2);

void setup() {
  // Do something here
  noLoop();
}

void draw() {
  PVector v2 = calc(vect1);
  println("Vect 1 is "+vect1+ " v2 is "+v2);
}

PVector calc(PVector v1) {
  return v1.normalize(null);



See the PVector developer's reference for full details.
Page Index Toggle Pages: 1