Inserting a vertex into a PShape

Unfortunately adding a vertex after a PShape has been created seems like it’s not possible right now. You can check out the full javadoc here. If you wanted you could create a class that extends PShape and edits the vertices array directly. This is probably more work than it’s worth your solution seems like a great way around the problem. I would probably just take it one step further and wrap the PShape in another class with an ArrayList to make it easier to keep track of. This also has the advantage you don’t have to keep track of when the shape needs to be updated. Here’s my basic idea for a class:

class PShapeContainer {
  ArrayList<PVector> vertices;
  PShape shape;
  PShapeContainer(ArrayList<PVector> vertices) {
    this.vertices = vertices;
    shape = new PShape();
    updateShape();
  }
  void updateShape() {
    PShape tempShape = new PShape();
    // do your shape creating stuff here
    shape = tempShape;
  }
  PShape getShape() {
    if (shape.getVertexCount() != vertices.size()) updateShape();
    return shape;
  }
  boolean addVertex(int index, PVector vertex) {
    if (index < vertices.size()) {
      vertices.add(index, vertex);
      return true;
    } else {
      return false;
    }
  }
}
2 Likes