A basic sketch that shows how to use millis() for basic animation, in this case a fade-in of a rect(). millis() returns the current runtime of the sketch in milliseconds. Left-click for Fade-In, Right-click for Fade-Out. The transparency (alpha channel of fill/stoke) is calculated evenly across the duration, meaning you only have to change 1 variable (delaytime) for adjusting the speed and fade. I wrote this from scratch as a learning activity some time ago, should be helpful to newcomers.
http://www.openprocessing.org/visuals/?visualID=30730
..continue for code..
<pre class="brush: java; title: ; notranslate" title="">//GLOBALS
int alphavalue;
int starttime;
int delaytime = 9255;
int curtime;
float count_up;
float count_down;
float calc_alpha;
void setup(){
size(400,180);
}
void draw()
{
background(0);
strokeWeight(10);
stroke(120,alphavalue);
fill(255,alphavalue);
rectMode(CORNER);
rect(245,34,130,100);
fill(255);
text("start time: " + starttime, 15, 45); // start time (runtime when mouse was first clicked)
text("delay time: " + delaytime, 15, 60); // delay time
text("count: " + ceil(count_up), 15, 75); // timer count
text("count down: " + ceil(count_down), 15, 90); // count down
text("current runtime: " + curtime, 15, 105); // current runtime in ms since sketch started
text("calculated alpha: " + calc_alpha, 15, 120); // alpha amount distributed over time
text("alpha: " + alphavalue, 15, 135); // actual alpha transparency
if(mousePressed) {
if (millis() - starttime < delaytime) {
count_up = (millis() - starttime); // timer count (difference from time first mousePressed occurs and the total runtime of sketch)
count_down = delaytime - count_up; // countdown since started (mousePressed())
if (mouseButton == LEFT) {
calc_alpha = 255 / (delaytime / count_up); // fade-in, calculate alpha value vs. duration
alphavalue = ceil(calc_alpha); // ceil rounds UP and returns the closest integer value
}
if (mouseButton == RIGHT) {
calc_alpha = 255 / (delaytime / count_down); // fade-out, calculate alpha value vs. duration
alphavalue = floor(calc_alpha); // floor rounds DOWN and returns the closest integer value
}
curtime = millis(); //report the current runtime only while loop is running. visual readonly only. ignoreable.
if (alphavalue == 0) { count_down = 0; count_up = delaytime;} //some precision is lost from float to int, so i reset the counters..
if (alphavalue == 255) {count_down = 0; count_up = delaytime; } //..for visual readout only, also ignoreable.
}
}
else {
//alphavalue = 0;
}
}
void mousePressed() {
starttime = millis(); // mousePressed() is only called once per press, unlike in draw
// if starttime was set in draw's mousePressed event, it would never end
}
void mouseReleased() {
redraw(); // start over
}
</pre>
<div class="addtoany_share_save_container addtoany_content_bottom">
<div id="" class="a2a_kit a2a_kit_size_32 addtoany_list a2a_target">
