Why do we use norm function?

edited October 2016 in Questions about Code

Namaste all,

I was trying to make an analog clock and came across this code :

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();
} 

I wanted to understand why have they used "norm" function for minute and hour hands? I know norm normalizes a number from another range into a value between 0 and 1. Why is it needed here?

Thanks!!

Tagged:

Answers

  • Answer ✓

    norm() is used here to translate seconds and minutes to the decimal system. So for example: If you have 1 hour and 30 minutes you can say: This are 1.5 hours.

    The same could be achieved if you divide by 60.

  • if you just used hour in line 33 then the arm would point to 3 from 3 o'clock until 3:59 before suddenly pointing to 4. adding the fractional part, calculated using the minutes, the arm will gradually move from 3 to 4 as the hour proceeds, like a real clock does.

    the same, to a lesser degree, with the minutes

  • Thanks benja. One more doubt, we are mapping second & minute from 0 to 60, shouldnt they be mapped from 0 to 59 coz thats the range of their value? shouldn't this gives an error since 60 is more than the function's range?

  • when I tried doing it form 0-59 the hands stopped for a sec and then moved again.

Sign In or Register to comment.