Created
November 18, 2016 17:23
-
-
Save nataliefreed/ddcce53a94cf0e171d0a4b47fb961c74 to your computer and use it in GitHub Desktop.
Stoplight timer example using millis()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Timer example using millis() */ | |
var timer; | |
var light_state = 0; | |
function setup() { | |
createCanvas(600, 600); | |
timer = millis(); | |
noStroke(); | |
} | |
function draw() { | |
background(255); | |
fill(100); | |
rect(width/2-50, 50, 100, 200); | |
//if time since last timer reset is greater than 1000 | |
if(millis() - timer > 1000) { | |
//change the light state (0, 1, 2, then back to 0, 1, 2...) | |
light_state = (light_state + 1) % 3; | |
//reset timer | |
timer = millis(); | |
} | |
//draw the stop light | |
stoplight(light_state); | |
} | |
function stoplight(s) { | |
var y; | |
switch(s) { | |
case 0: | |
fill(0, 255, 0); | |
y = 100; | |
break; | |
case 1: | |
fill(255, 255, 0); | |
y = 150; | |
break; | |
case 2: | |
fill(255, 0, 0); | |
y = 200; | |
break; | |
default: | |
break; | |
} | |
ellipse(width/2, y, 50, 50); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment