Order of using mult(0) & add() for vectors in processing

I am sorry in advance if this is a trivial question as I am confused with the output displayed.

void setup(){
  size(800,800);
}


void draw(){
  background(0);
  //PVector v = PVector.fromAngle(PI);
  PVector v = new PVector();
  v.mult(150);
  v.add(width/2,height/2);
  
    
  stroke(255);
  fill(255);
  ellipse(v.x,v.y,15,15);
}

This is simple sketch of drawing ellipse using vector. I first set magnitude then translate it to the center by adding width/2 & height/2. I see the ellipse in the center.

 If I remove mult(). The output is the same.
But if I flip it & used add(width/2,height/2) before mult (). The output has no ellipse.
I can't seem to understand what's happening here.

1 Like

After PVector v = new PVector();, you have a vector who’s X value is 0, and Y value is also 0.

After v.multi(150), you have vector that is STILL (0,0)! This multiplication does nothing! A zero vertor times 150 is still a zero vector!

After a.add(width/2,height/2);, your vector now has an X of 400 and a Y of 400.

When you draw an ellipse, it appears at (400,400).


If you swap the add() and multi(), what happens?

The vector starts at (0,0) again.

After the add, it’s (400,400).

After the multi, it’s (60000,60000). (Actually it’s not. I’ll leave it to you to work out what its values really are, and why. Still, they are big numbers.)

And you draw an ellipse at (60000,60000)… which isn’t a position in the view-able area of your sketch!

3 Likes

@TfGuy44 Yes thanks got it! Although when PVector.fromAngle is used after add & mult, it shows the ellipse at origin.

void setup(){
  size(800,800);
}


void draw(){
  background(0);
  
  PVector v = new PVector();
  
  v.add(width/2,height/2);
  v.mult(1.4);
  v = PVector.fromAngle(PI,v);
  
    
  stroke(255);
  fill(255);
  ellipse(width/2,height/2,2,2);
  ellipse(v.x,v.y,15,15);
}


void setup() {
  size(800, 800);
}


void draw() {
  background(0);

  PVector v = new PVector();

  println( "Initial: " + v.x + " " + v.y );

  v.add(width/2, height/2);

  println( "After add(): " + v.x + " " + v.y );

  v.mult(1.4);

  println( "After multi(): " + v.x + " " + v.y );

  v = PVector.fromAngle(PI, v);

  println( "After fromAngle(): " + v.x + " " + v.y );


  stroke(255);
  fill(255);
  ellipse(width/2, height/2, 2, 2);
  ellipse(v.x, v.y, 15, 15);
}

Outputs:

Initial: 0.0 0.0
After add(): 400.0 400.0
After multi(): 560.0 560.0
After fromAngle(): -1.0 -8.742278E-8

This is correct.

Don’t confuse an ellipse at (0,0) with one at (-1,0)!

1 Like