Hi,all
I am new to controlP5 and just started with doing a responsive polygon in processing.
I gave it a slider to control the side of the polygon and then give its default number as 3 in setup(), however, if I want to change it later on, I cannot go back to the setup(), so it will create problem as 'arrayIndexOutofBound' as in draw().
Here is the code:
Code:ControlP5 controlP5;
int backgroundColor = color(200);
int strokeColor = color(0,0,0);
boolean press = true;
boolean fillColor = false;
int n = 3;
int radius = 100;
float[] px = new float[n];
float[] py = new float[n];
void setup(){
size(600,600);
controlP5 = new ControlP5(this);
control();
float angle = 2 * PI / n; //divide the circle in n sect
for(int i =0; i< n; i++){
px[i] = width/2 + radius * sin(angle*i);
py[i] = height/2 + radius * cos(angle*i);
}
rectMode(CENTER);
}
void draw (){
if(press == true){
background(backgroundColor);
}
stroke(strokeColor);
if(fillColor == false){
noFill();
}
//strokeWeight(2);
beginShape(POLYGON);
for(int i = 0; i < n; i++)
vertex(px[i],py[i]);
endShape(CLOSE);
for(int i=0; i<n; i++){
if(dist(mouseX,mouseY,px[i],py[i])<20)
stroke(255,0,0);
else
stroke(strokeColor);
rect(px[i],py[i],5,5);
}
}
void mouseDragged(){
for(int i=0; i<n; i++)
if(dist(mouseX,mouseY,px[i],py[i])<20){
px[i] += (mouseX-pmouseX); //push only
py[i] += (mouseY-pmouseY);
px[i] = constrain(px[i],5,width-5);
py[i] = constrain(py[i],5,height-5);
}
}
import controlP5.*;
void control(){
//strokeColor
controlP5.addBang("bang1",20,60,80,20).setTriggerEvent(Bang.RELEASE);
controlP5.controller("bang1").setLabel("stokeColor");
//fill
controlP5.addBang("bang2",20,100,80,20).setTriggerEvent(Bang.RELEASE);
controlP5.controller("bang2").setLabel("fill");
//background
controlP5.addNumberbox("numberboxA",backgroundColor,20,20,80,20).setId(1);
controlP5.controller("numberboxA").setLabel("changeBackground");
controlP5.controller("numberboxA").setMax(255);
controlP5.controller("numberboxA").setMin(0);
//side
controlP5.addSlider("sliderA",2,20,5,20,140,80,20).setId(2);
controlP5.controller("sliderA").setLabel("side");
}
void numberboxA(){
int Color = (int)random(255);
backgroundColor = color(Color);
//println("### bang(). a bang event. setting background to "+ Color);
controlP5.controller("numberboxA").setValue(Color);
press = true;
}
void bang1(){
int Color = (int)random(255);
strokeColor = color(Color);
}
void bang2(){
if(fillColor == false){
fillColor = true;
fill(200,50);
}
else{
fillColor = false;
}
}
//void sliderA(int theValue){
// n = theValue;
//}
void controlEvent(ControlEvent theEvent) {
switch(theEvent.controller().id()) {
case(2):
n = (int)(theEvent.controller().value());
//println("n" + n);
break;
}
}