Average all X Values of a PShape?

edited April 2015 in How To...

I am trying to find the approximate center of my 3d PShape. I think to find said vertex, I'd need to average all the x coordinates, average all the y coordinates, and average all the z coordinates to get the center x y z. How would I write a for loop that does this?

Tagged:

Comments

  • Always post your code when you have a discussion in Programming Questions

    I made an example of how to find the average x position below (using PVectors), the code would just be repeated for y and z. Even if you are not using PVectors you should be able to use the same idea

    void setup() {
      size(100, 100);
    
      final int NUM_THINGS = 100;
    
      // Random coordinates for 100 things
      PVector[] p = new PVector[NUM_THINGS];
      for (int i = 0; i < NUM_THINGS; i++)
        p[i] = new PVector(random(-10, 10), random(-10, 10), random(-10, 10));
    
      // Initialize the average for x (do this for y and z later)
      float averageX = 0.0;
    
      // Add up all the x
      for (int i = 0; i < NUM_THINGS; i++)
        averageX += p[i].x;
    
      // Divide by the number of things to get the average
      averageX /= NUM_THINGS;
    }
    
Sign In or Register to comment.