Showing timer function inside GUI

11 views (last 30 days)
Austin Hague
Austin Hague on 27 Nov 2015
Answered: Geoff Hayes on 27 Nov 2015
Hey y'all.
My problem I'm running into is how to show a timer inside my GUI. Currently I am creating a game for class and the game stops after 60 seconds. I am displaying the score using the title() function, but can't find a way to show the time every time I update the graphics. Any Solutions would be great!
P.S. If you have a better way of showing the time and score please be sure to share.
Below is a snipet of my code:
% Timer Function
t = timer('TimerFcn', 'stat=false; disp(''Game Over'')','StartDelay',60);
start(t)
stat=true;
% Later when I update the graphics
time = floor(t);
title([{'Time: ',num2str(time);'Score: ',num2str(Score)}]);

Answers (1)

Geoff Hayes
Geoff Hayes on 27 Nov 2015
Austin - what time are you trying to show? The current time or the elapsed time? In the above code,
t = timer(...
t should be the timer object, so trying to call floor on this object should fail with the error
Undefined function 'floor' for input arguments of type 'timer'.
If you want to show the elapsed time since the start of the game (or start of the timer), then you could use the now function. Suppose you call now as soon as you start the timer
start(t);
gameStartTime = now;
When you are ready to display the elapsed time, then get the current time and compare it with the start time
currentTime = now;
elapsedTimeSec = floor((currentTime - gameStartTime)*86400);
title([{'Time: ',num2str(elapsedTimeSec);'Score: ',num2str(Score)}]);
Since now returns a serial date number which represents the whole and fractional number of days from a fixed, preset date, then to convert it to seconds, we multiply by 86400 (=24 hours * 60 minutes * 60 seconds).

Categories

Find more on Just for fun in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!