Login | Register

Create a timer

July 25, 2006, 15:03 by Calle
[loading]
-->
Timers are highly useful in any sort of game. For an example, it is expected to have a timer in a racing game. Other will not do. Game Maker got several ways of creating a timer, I will show you two of them. First of all, using alarm.

Alarms are perfect for the timer purpose. You set them like this:

alarm[0] = 1

0 is exchangeable and could be any number between 0 and 9.1 is the number of steps until the code in alarm event 0 is executed. Therefore, if we want to create a timer we need to decide how detailed it should be. Let’s say we want to count seconds, then we also want to execute the alarm event one time every second.

alarm[0] = room_speed

As I said we set the alarm to the number of steps until execution, but as the game does not always take the same amount of steps per seconds we will need to use a variable that is always correct. Room_speed is perfect, because that’s the variable that actually decides how many steps the game takes per second. By standard it is 30. If we wanted a minute we could set it to room_speed*60 for an example.

timer +=1;
alarm[0] = room_speed;


That’s the code we might use in the alarm event. First of all it sets timer to +1, that means +1 second as the code is only executed one timer per second. Then we need to set the alarm event again, so that it will run next second again.

<b>Now the second solution.</b> This is the one I prefer, although as a beginner I always used the other. This is shorter, and it has a possibility to output more accurate results. In fact, the more steps per second (the higher the room_speed) that the game takes, the more accurate result it gets. The only code needed, is this:

timer+=1;
time = timer/room_speed;


Put the code in step event, and it will count the number of steps, it is the divided with the number of steps per second and so we get the number of seconds that the code has been executed. Now chances are also you get a lot of numbers: 2.34983 with a point, which you may find unnecessary, so you might want to use round().

Example:
http://gmtutorials.com/files/timerex.gm6

Comments

Loading comments... [loading]
.
Users logged in:

game maker articles, game maker examples, game maker tutorials, gmtutorials, game maker questions and answers, game maker crash course, how to create games