For Loop That Accesses Every Third Vertex?

edited April 2015 in Questions about Code

Basically I want to make a for loop that accesses every third (or whatever number) vertex and creates PVectors that I can multiply so I can deform them, in the same manner that I deformed my "p" PVector using mult(). I just don't know how to write a for loop to access those verts. Thanks for any help!

// Copywrite Bret Merritt, 2015
PShape objShape;
float rotX;
float rotY;

void setup() {
  size(1280, 768, P3D);
  objShape = loadShape("Wolf_fixed.obj");
  stroke(200);
  strokeWeight(.7);
  smooth(8);
}

void draw() {
  stroke(200);
  background(20);
  translate(width/2, height/1.7, 300);
  rotateX(PI);
  rotateY(rotX);

  PShape s = createShape();
  s.beginShape(TRIANGLES); 
  for (int i=0; i<objShape.getChildCount (); i++) {
    if (objShape.getChild(i).getVertexCount() ==3) {
      for (int j=0; j<objShape.getChild (i).getVertexCount(); j++) {

        PVector p = objShape.getChild(i).getVertex(j);

        // random deform
        p.mult(random(.95, 1.05));

       // random fill per triangle 
//        s.fill(random(0, 200));

        s.vertex(p.x, p.y, p.z);
      }
    }
  }

  s.endShape(CLOSE);
  shape(s);
}

void mouseDragged() {
  rotX += (mouseX - pmouseX) * 0.01;
  rotY -= (mouseY - pmouseY) * 0.01;
}
Tagged:

Answers

  • Answer ✓

    Use i+=3 instead of i++? Or keep using i++ and wrap your for loop's body inside a if(i%3==0){}.

  • Thank you for the quick response and easy fix! Now I need to write a for loop that avoid all third verts so I'm not being inefficient...

  • That's what using I+=3 does!

    You know how a for loop works, right? It has three parts:

    for(A; B; C){}
    

    A runs once when the for loop is first encountered. B runs at the start of the loop. If it evaluates to true, the loop body runs again. If not, then the for loop is done. C runs after the body is run, usually to update the conditions that B is testing.

    So this: for( int i = 0; i < 4; i+=2){ println("body" + i); } means this:

    int i = 0; // A
    while( i < 4){ // B
      println("body" + i); // Body.
      i += 2; // C
    }
    
Sign In or Register to comment.