I am trying to achieve an animated spiral curve on Processing, so that the curve is built gradually within each draw() function. I have created successfully the curve as a static shape - now I am trying to go one step further.
Unfortunately, though, my code doesn't seem to be working, despite my efforts. After some waiting time I get the shape static again along with the following error message:
You must use beginShape() or beginShape(POLYGON) before curveVertex()
In contrast to this message, I have already a beginShape() instruction (maybe in the wrong place?)
Here is my code:
float x,y;
float stepSize;
float angle;
int counter;
void setup() {
size(900, 600);
background(255);
frameRate(30);
smooth();
//noStroke();
stroke(0);
x = 0;
y = 0;
stepSize = 6;
angle = radians(270);
counter = 0;
}
void draw() {
translate(width/3, height/2);
if (counter == 0) {
beginShape();
curveVertex(x, y); // initial control point
} else {
if (stepSize > 1.0) {
curveVertex(x, y);
x = x + cos(angle) * stepSize;
y = y + sin(angle) * stepSize;
stepSize = stepSize * 0.99;
angle = angle - radians(1.5);
} else {
// return to previous x,y values for last control point
angle = angle + radians(1.5);
stepSize = stepSize / 0.99;
y = y - sin(angle) * stepSize;
x = x - cos(angle) * stepSize;
curveVertex(x, y); // last control point
endShape();
}
}
counter++;
}
Thanks in advance for any help you could provide! - Ilias
It seems very strange to try to split a beginShape()
, curveVertex()
, endShape()
group between multiple calls to the draw()
function.
Instead, you should keep track of every point you want to draw- an ArrayList<PVector>
would come in handy here. To draw your curve, just iterate over that ArrayList
and draw every point. To extend the curve, just add a PVector
to it.
float stepSize = 6.0;
float angle= radians(270);
ArrayList<PVector> points = new ArrayList<PVector>();
void setup() {
size(900, 600);
frameRate(30);
points.add(new PVector(0, 0));
}
void draw() {
background(255);
translate(width/3, height/2);
//draw previous points
beginShape();
for (PVector point : points) {
curveVertex(point.x, point.y);
}
endShape();
if (stepSize > 1.0) {
//add a new point
PVector prevPoint = points.get(points.size()-1);
float x = prevPoint.x + cos(angle) * stepSize;
float y = prevPoint.y + sin(angle) * stepSize;
points.add(new PVector(x, y));
stepSize = stepSize * 0.99;
angle = angle - radians(1.5);
}
}
You could get away with only storing the most recently drawn point and accumulating the draw calls, but redrawing every point is probably the most common approach to this type of problem.