Random functions/classes #6: Analog Clock

--# Time
Time = class()

function Time:init()
    self.size = clock.size
    self.time = os.date("*t")
    
    self.hour = function()
        if self.time.hour>12 then
            return self.time.hour-12
        end
        
        return self.time.hour
    end
    
    self.min = function()
        return self.time.min
    end
    
    self.sec = function()
        return self.time.sec
    end
end

function Time:draw()
    self.time = os.date("*t")
    local h,m,s = self.hour(),self.min(),self.sec()
    
    pushMatrix()
    pushStyle()
    
    translate(WIDTH/2,HEIGHT/2)
    
    stroke(0)
    self:drawHand(m*-6,self.size/2.4) -- minute hand
    self:drawHand(-30*(h+m/60),self.size/5) -- hour hand
    stroke(255, 0, 0, 255)
    self:drawHand(s*-6,self.size/2.4) -- second hand
    
    popStyle()
    popMatrix()
end

function Time:drawHand(r,l)
    pushStyle()
    pushMatrix()
    
    rotate(r)
    strokeWidth(5)
    line(0,0,0,l)
    
    popMatrix()
    popStyle()
end


--# Clock
Clock = class()

function Clock:init(x,y,size)
    self.x = x
    self.y = y
    self.size = size
end

function Clock:draw()
    pushMatrix()
    
    translate(self.x,self.y)
    
    fill(255)
    ellipse(0,0,self.size)
    fill(0)
    ellipse(0,0,15)
    fontSize(self.size/12)
    text("3",self.size/2.4,0)
    text("6",0,-self.size/2.4)
    text("9",-self.size/2.4,0)
    text("12",0,self.size/2.4)
    
    for i = 1,12 do -- draw the hash marks
        local s = self.size/120
        if i%3==0 then
            s = self.size/40
        end
        
        self:makeHash(0,self.size/(15/7),i*30,s)
    end
    
    popMatrix()
end

function Clock:makeHash(x,y,r,s)
    pushMatrix()
    pushStyle()
    
    rotate(r)
    stroke(0)
    strokeWidth(s)
    line(x,y,x,y+self.size/60)
    
    popStyle()
    popMatrix()
end

--# Main
-- Clock
displayMode(FULLSCREEN)
function setup()
    clock = Clock(WIDTH/2,HEIGHT/2,600)
    time = Time()
end

function draw()
    background(40, 40, 50)
    
    clock:draw()
    time:draw()
end

@Doge Nice clock. You should change the code so the red second hand draws above the other hands.

I updated the code above and added:

  • support for any size clock
  • the program will now draw the second hand last so it looks like it's on top (like a real clock)

@Doge Nice. The second hand now looks a lot better since it stays on top. Your next challenge is the size of the hands. When I change the size of the clock, the width of the hands don’t change. When the clock is small, the hands look too wide compared to the face of the clock. Also, make the size of the clock change by using a parameter slider.