59

Using classes.

class led{

int x;

int y;

int r;

long now = millis();

//constructor

led(int xPos, int yPos, int rate){

x = xPos;

y = yPos;

r = rate;

}

void blink(int myX, int myY, int myR){

x = myX;

y = myY;

r = myR;

if (millis() < now + r){

fill (150);

}

else if (millis() < (now + 2*r)){

fill (0);

}

ellipse(x,y,20,20);

if (millis() > (now + 2*r)){

now = millis();

}

}

}

led led1;

led led2;

led led3;

int x=320, y=240;


void setup(){

size (640, 480);

led1 = new led(1,1,1);

led2 = new led(0,0,0);

}

void draw(){

background(100,100,100);

led1.blink(mouseX, mouseY, 500);

if(keyPressed && key=='a'){

x--;}

led2.blink(x, y, 200);

}

This code creates 2 blinking circles using classes. It is very similar to the code from 58. The class has 3 variables, x position, y position, and the rate of blinking.

Instead of using delay(t) the class uses millis() - the amount of time that has passed once the sketch began to time the blinking. If we use delay(t) the program will still 'hang' for t milliseconds.

The draw() loop is incomplete. If you run this code as-is, you will see that one led is moved with the mouse. The second only moves left when you press the 'a' key on your keyboard. You need to finish the code so that the led can be moved right, up, or down.


Challenge 59

Complete this code so that the led can be moved right, up or down using the 'd', 'w' and 'x' keys.