2015-10-08 2 views
1

Я использую Processing 3.0b5 для создания анимации, предназначенной для Интернета. В рамках этой анимации я создаю собственный класс, затем создаю массив объектов этого класса. Эти объекты оказываются прямоугольными.массив недоступен в функции Processing.js mousePressed()

Один из прямоугольников обозначается как кнопка, которая перезапускает анимацию. В среде обработки он работает хорошо. Однако, когда я запускаю анимацию на веб-странице, используя либо файл .pde ИЛИ, включая код на самой веб-странице, все работает над анимацией, кроме кнопки, и я не могу понять, почему.

Функция кнопки реализована с помощью функции mousePressed(). Ошибка, которую я получаю, состоит в том, что массив, который содержит прямоугольники, не существует. Однако массив является глобальной переменной и даже используется в других функциях программы. Похоже, что он просто недоступен в функции mousePressed() по какой-то причине. Если кто-нибудь может дать мне некоторое руководство, я был бы очень благодарен.

Полный исходный код обработки приведен ниже. Чтобы увидеть функция кнопки НЕ работает в сети, вы можете перейти к www.koeziris.com

//Global Vars 
float canvasWidth = 700; //don't use this line in website version 
float canvasHeight = 500; //don't use on website version 
int numElem = 250; 
int numBins = 18; 
int j = 0; //draw loop counter 
int yTravTime = 200; // the number of iterations until elements reach their final y position 
float[] binElem = new float[numBins+1]; 
Element[] elem = new Element[numElem]; 

//for buttons and color 
int reButton = 100; 

//for histogram collapse and expand 
boolean clicked = false; 
boolean fin = false; //has the histogram reached its final position once? 
int clickcounter = 0; 

void setup() { 
size(700, 500); 
for (int i = 0; i < numElem; i++) { 
int bin = 10 + round(constrain(randomGaussian() * 3, -9, 9)); //determines bin of each element 
binElem[bin-1]++; 
elem[i] = new Element(color(255, 10), round(bin * canvasWidth/numBins) - canvasWidth/(2 * numBins), -1000*i/numElem, bin, 0, binElem[bin-1]); //creates each element 
} 
} 

void draw() { 
background(0); 
for (int i = 0; i < numElem; i++) { 
    elem[i].move(); 
    elem[i].display(i); 
    j += 1; 
} 
} 

void mousePressed() { 
clicked = !clicked; 
//println("clicked= " + str(clicked)); 
clickcounter += 1; 
//println(str(clickcounter)); 

float reButtonXl = elem[reButton].xpos - elem[reButton].elemW/2; 
float reButtonXr = elem[reButton].xpos + elem[reButton].elemW/2; 
float reButtonYt = elem[reButton].yposFinal; //this works, but I don't really know why. Since drawing rectangles in "center" mode, I would think I need to subtract off 1/2 of the height 
float reButtonYb = elem[reButton].yposFinal + (elem[reButton].elemH)*2; //this works, but shouldn't. Should need to add 1/2 the height 
if (clicked) { 
println("\n"); 
println(str(clicked)); 
println("mouseX =" + str(mouseX)); 
println("mouseY =" + str(mouseY)); 
println("reButtonYb =" + str(elem[reButton].yposFinal + elem[reButton].elemH/2)); 
println("reButtonYt =" + str(elem[reButton].yposFinal - elem[reButton].elemH/2)); 
println("elemH = " + str(elem[reButton].elemH)); 
println("yposFinal = " + str(elem[reButton].yposFinal)); 

} 
if (mouseX >= reButtonXl && mouseX <= reButtonXr && mouseY <= reButtonYb && mouseY >= reButtonYt) { 
    println("target clicked"); 
    background(0); 
    j = 0; //draw loop counter 
    binElem = new float[numBins+1]; 
    Element[] elem = new Element[numElem]; 

    //for histogram collapse and expand 
    clicked = false; 
    fin = false; //has the histogram reached its final position once? 
    clickcounter = 0; 
    setup(); 
} 
} 

class Element { 
float elemW = canvasWidth/numBins - numBins * 0.1; 
float elemH = 5.0; 
color c; 
float xpos; 
float ypos; 
float yposFinal; 
int eBin; 
float xspeed; 
float yspeed; 
float binElem; 
float spacing = 0.4*elemH; 
//The Constructor 
Element(color c_, float xposInit_, float yposInit_, int eBin_, float xspeed_, float binElem_) { 
    c = c_; 
    xpos = xposInit_; 
    ypos = yposInit_; 
    eBin = eBin_; 
    binElem = binElem_; 
    yposFinal = canvasHeight - binElem * (elemH+spacing) + elemH/2; 
    xspeed = xspeed_; 
    yspeed = (canvasHeight-yposInit_+canvasHeight-yposFinal)/yTravTime; 
} 

void display(int i) { 
    stroke(100); 
    // Logic for blinking element. Only blinks when histogram has not been collapsed by clicking 
    // and if all elements are in their final position and the time or iteration constraint is met. 
    // would be best if iteration rather than time constraint since that is how movement is controlled. 
    if (ypos==yposFinal && millis() > 6000 && i == reButton){ 
    fill(#6086ED, 200 + (55*sin(millis()/600.0))); 
    } else { 
    fill(c); 
    } 
    rectMode(CENTER); 
    rect(xpos, ypos, elemW, elemH); 
    //println(j); 
} 

void move() { 

    xpos += xspeed; 
    // Execute once clicked to collapse histogram. Fin is boolean indicator that the histogram was completed at least once 
    if (clicked && fin){ 
    yspeed = 0.1*(canvasHeight-elemH-ypos); 
    if (canvasHeight - elemH - ypos > 1) { 
     ypos += yspeed; 
     //println("1st IF, 1st sub condition"); 
    } else { 
     ypos = canvasHeight - elemH; 
     //println("1st IF, 2nd sub condition"); 
    } 
    //Logic for re-expanding the collapsed histogram 
    } else if(clickcounter > 0 && abs(ypos - yposFinal) > 1.0) { 
    yspeed = -0.1 * (ypos - yposFinal); 
    ypos += yspeed; 
    //Logic for stationary re-expanded histogram 
    } else if(clickcounter > 0 && abs(ypos - yposFinal) < 1.0) { 
    yspeed = 0; 
    ypos = yposFinal; 
    // create the bounce effect 
    } else if(ypos > canvasHeight - elemH/2) { 
    yspeed = -yspeed; 
    ypos += yspeed; 
    //println("3rd IF"); 
    // keep elements moving upwards after the bounce 
    } else if (ypos > yposFinal && yspeed < 0) { 
    ypos += yspeed; 
    //println("4th IF"); 
    // move elements into final hisotgram position 
    } else if (ypos < yposFinal && yspeed < 0) { 
    ypos = yposFinal; 
    yspeed = 0; 
    fin = true; 
    //println("5th IF"); 
    } else { 
    ypos += yspeed; 
    //println("6th IF"); 
    } 
} 
} 

ответ

0

Мое предположение было бы, что вы назвать две переменные то же самое. Это хорошо в Java (работает обработка на рабочем столе), но может привести к странному поведению в JavaScript.

Я заметил, что вы создаете еще один массив с именем elem в строке 61, который вы никогда не используете. Я бы удалил это, а затем ищем любые другие переменные, которые можно назвать одним и тем же.

+0

Спасибо! Линия 61 действительно была проблемой. Я удалил его, и он отлично работает. – Drwhit

Смежные вопросы