## Example of using vectors

Hi, I’ve been asked for a few more examples of using maths in Processing programs.
This is one example, in which 3D boxes are drawn, but they get bigger depending on how far they are from the middle. I calculate the distance from the midpoint using vectors then apply it to the scale of the box.
Marco

```  import processing.opengl.*; /* This program show how to draw objects of different heights depending on their distance away from a point it shows how to use vectors, and the PVector.dist method */ PVector startPoint = new PVector(0, 0, -300); void setup() { size(500, 500, OPENGL); /* initial camera setup */ camera(300, 300, 1000, 300, 300, 0, 0, 1, 0); } void draw() { background(255); strokeWeight(5); /* camera stuff from previous weeks //start tranforming the camera*/ beginCamera(); /* the keyboard controls forward and backward movement*/ if (keyPressed) { /* w for forward, s for back*/ if (key == 'w') translate(0, 0, -1); if (key == 's') translate(0, 0, 1); } /* the mouse controls rotation */ if (mousePressed) { /* yaw */ rotateY(-(PI/16)*float(mouseX-pmouseX)/300); } endCamera(); /* go from a negative position to a positive one */ for (int x = -1000; x < 1000; x += 100) { /* the position of the box */ PVector pos = new PVector(x, 0, -300); /* find the distance between the start point and the box we will use this as the height of the box */ float d = PVector.dist(pos, startPoint); /* draw the box */ pushMatrix(); /* move to the correct position */ translate(pos.x, pos.y, pos.z); /* scale so its height is multiplied by d */ scale(100, d, 100); box(1, 1, 1); popMatrix(); } }```
Send article as PDF