I am using Processing 2.08 on mac. I am trying to create a PShape using the createShape function as given in the documentation.
PShape s;
void setup(){
size(500,500);
s = createShape();
s.beginShape(QUADS);
s.fill(0);
s.vertex(100,100);
s.vertex(100,300);
s.vertex(300,300);
s.vertex(300,100);
s.endShape();
}
void draw(){
shape(s);
}
But this program throws NullPointerException. Upon looking up on the Processing.org forum I found a thread saying that the new processing library has problem with this one.
ref: https://forum.processing.org/topic/changes-to-pshape-in-2-08
How do I make this work? Is there any workaround?
Thanks
From the documentation:
Datatype for storing shapes. Processing can currently load and display
SVG (Scalable Vector Graphics) and OBJ shapes. Before a shape is used,
it must be loaded with the loadShape() function. The shape() function
is used to draw the shape to the display window. The PShape object
contains a group of methods, linked below, that can operate on the
shape data. OBJ files can only be opened using the P3D renderer.
You can find the reference here: http://processing.org/reference/PShape.html
In short, for now, you can't use PShape without first creating a shape elsewhere.
You could just create an image independently, save it on file and then load it with PShape. Its a hack but it makes it possible to use PShape at least until they can come up with a more proper fix.
I addition to nickecarlo's answer, you could use PGraphics:
PGraphics s;
void setup(){
size(500,500);
s = createGraphics(width,height);
s.beginDraw();
s.beginShape(QUADS);
s.fill(0);
s.vertex(100,100);
s.vertex(100,300);
s.vertex(300,300);
s.vertex(300,100);
s.endShape();
s.endDraw();
}
void draw(){
image(s,0,0);
}
or implement your own Shape class.
Here's a very crude example:
Shape s = new Shape();
Shape s2 = new Shape();
void setup(){
size(500,500);
s.addVertex(100,100);
s.addVertex(100,300);
s.addVertex(300,300);
s.addVertex(300,100);
s2.addVertex(350,100);
s2.addVertex(450,100);
s2.addVertex(450,200);
s2.addVertex(350,200);
}
void draw(){
s.draw();
s2.draw();
}
class Shape{
ArrayList<PVector> vertices = new ArrayList<PVector>();
void addVertex(float x,float y){
vertices.add(new PVector(x,y));
}
void draw(){
pushStyle();
beginShape(QUADS);
fill(0);
for(PVector v : vertices) vertex(v.x,v.y);
endShape();
popStyle();
}
}