Translating while creating a PShape

I want to create a PShape in tandem with the translate function so that after each vertex is placed, I can translate to that vertex and create the next vertex from that offset. I do this often with PGraphics and it works fine but I use the line function instead of vertex.

Using a PGraphic this draws a straight line 200px long.

for(int i = 0; i<200;i++)
{
    pg.line(0,0,0,-1);
    pg.translate(0,-1);
}

I want to do the same thing but with a PShape and also using pushMatrix and popMatrix later on. I have tried this and it doesn't seem to work.

for(int i = 0; i<200;i++)
{
    s.vertex(0,-1);
    s.translate(0,-1);
}

Shouldn't this allow me to create a vertex at 0,-1, translate to 0,-1 and create another vertex at 0,-1 which is really just 0,-2 if I had not translated... so on.

I then draw it to a PGraphic and display it but it is always blank. What am I missing? Here is a full version of the code I am using to test this.

PShape s; 
PGraphics img;
void setup() {
  size(500, 500);
  img = createGraphics(100,100);
  s = createShape();
  s.beginShape();
  for(int i = 0; i<200;i++)
  {
    s.vertex(0,1);
    s.translate(0,-1);
  }
  s.endShape();

  img.beginDraw();
  img.shape(s);
  img.endDraw();
}

void draw() {
  image(img,250,250);
}

The reason I want to do this is beacuse I am drawing generated shapes that I don't know the size and shape of until they are drawn. I want to use a PShape because it is vector based so I can scale and move it as much as I want.

Tagged:

Answers

  • @bogabrain -- re:

    ...this is not how PShape.translate() works! It is a simple offset variable, it is cumulative, and it persists.

    Specifies an amount to displace the shape. [...] Subsequent calls to the method accumulates the effect. For example, calling translate(50, 0) and then translate(20, 0) is the same as translate(70, 0). -- https://processing.org/reference/PShape_translate_.html

    Your second problem is that you are drawing off the edge of your PGraphics surface, so your pixels aren't recorded. You need to make it the same size as your canvas and center before drawing.

    PShape s; 
    PGraphics img;
    void setup() {
      size(500, 500);
      img = createGraphics(500,500);
      s = createShape();
      s.beginShape();
      s.translate(250,250);
      for(int i = 0; i<200;i++)
      {
        s.vertex(0,-i);
      }
      s.endShape();
    
      img.beginDraw();
      img.shape(s);
      img.endDraw();
    }
    
    void draw() {
      image(img,0,0);
    }
    
  • edited April 2017

    With all due respect, all you're drawing is a straight line. Surely, that's not what you wanted?

Sign In or Register to comment.