Variables

Simple Clock

A very simple clock – just using variables

void setup() {

  size(200, 200);

  stroke(255);

  smooth();

}

void draw() {

  background(0);

  fill(80);

  noStroke();

  // Angles for sin() and cos() start at 3 o'clock;

  // subtract HALF_PI to make them start at the top

  ellipse(100, 100, 160, 160);

  float s = map(second(), 0, 60, 0, TWO_PI) - HALF_PI;

  float m = map(minute(), 0, 60, 0, TWO_PI) - HALF_PI;

  float h = map(hour() % 12, 0, 12, 0, TWO_PI) - HALF_PI;

  stroke(255);

  strokeWeight(1);

  line(100, 100, cos(s) * 72 + 100, sin(s) * 72 + 100);

  strokeWeight(2);

  line(100, 100, cos(m) * 60 + 100, sin(m) * 60 + 100);

  strokeWeight(4);

  line(100, 100, cos(h) * 50 + 100, sin(h) * 50 + 100);

}

Clock

This is a clock example. Classic sketch format

int cx, cy;
float secondsRadius;
float minutesRadius;
float hoursRadius;
float clockDiameter;

void setup() {
  size(640, 360);
  stroke(255);
  
  int radius = min(width, height) / 2;
  secondsRadius = radius * 0.72;
  minutesRadius = radius * 0.60;
  hoursRadius = radius * 0.50;
  clockDiameter = radius * 1.8;
  
  cx = width / 2;
  cy = height / 2;
}

void draw() {
  background(0);
  
  // Draw the clock background
  fill(80);
  noStroke();
  ellipse(cx, cy, clockDiameter, clockDiameter);
  
  // Angles for sin() and cos() start at 3 o'clock;
  // subtract HALF_PI to make them start at the top
  float s = map(second(), 0, 60, 0, TWO_PI) - HALF_PI;
  float m = map(minute() + norm(second(), 0, 60), 0, 60, 0, TWO_PI) - HALF_PI; 
  float h = map(hour() + norm(minute(), 0, 60), 0, 24, 0, TWO_PI * 2) - HALF_PI;
  
  // Draw the hands of the clock
  stroke(255);
  strokeWeight(1);
  line(cx, cy, cx + cos(s) * secondsRadius, cy + sin(s) * secondsRadius);
  strokeWeight(2);
  line(cx, cy, cx + cos(m) * minutesRadius, cy + sin(m) * minutesRadius);
  strokeWeight(4);
  line(cx, cy, cx + cos(h) * hoursRadius, cy + sin(h) * hoursRadius);
  
  // Draw the minute ticks
  strokeWeight(2);
  beginShape(POINTS);
  for (int a = 0; a < 360; a+=6) {
    float angle = radians(a);
    float x = cx + cos(angle) * secondsRadius;
    float y = cy + sin(angle) * secondsRadius;
    vertex(x, y);
  }
  endShape();
}

Using Variables

This a simple example on how to use variables. It saves you having to work out all the points – you can use variables to keep it simple. And if you want to change the position of something you can just change the variables

size(640, 360);
background(0);
stroke(153);
strokeWeight(4);
strokeCap(SQUARE);

int a = 50;
int b = 120;
int c = 180;

line(a, b, a+c, b);
line(a, b+10, a+c, b+10);
line(a, b+20, a+c, b+20);
line(a, b+30, a+c, b+30);

a = a + c;
b = height-b;

line(a, b, a+c, b);
line(a, b+10, a+c, b+10);
line(a, b+20, a+c, b+20);
line(a, b+30, a+c, b+30);

a = a + c;
b = height-b;

line(a, b, a+c, b);
line(a, b+10, a+c, b+10);
line(a, b+20, a+c, b+20);
line(a, b+30, a+c, b+30);