FPS (frames-per-second) is a value that shows the current frame rate. Scratch targets 30 FPS however it can be lower on projects that are more demanding of system resources. Showing the current frame rate can be useful for debugging the performance of such projects.
The duration of a frame is usually measured in seconds (seconds-per-frame instead of frames-per-second) and given the name delta time. Delta time is useful for making animations run consistently in real-time.
FPS is the inverse of delta time and vise versa, so and .
Making an FPS Variable
Reset Timer Method
This script measures the duration of the frame with the timer. FPS is calculated from this every iteration of the loop (every frame) and stored in a variable.
| In this script the timer is reset every frame which prevents the use of the timer elsewhere in the project. |
when flag clicked forever set [FPS v] to ((1) / (timer)) reset timer end
| A round () block can make the FPS number easier to read. |
Timer in Use Method
If the timer is needed elsewhere, the following script can be used. Instead of resetting the timer, a variable is used to store the previous time, to be subtracted from the current time.
when flag clicked set [previous time v] to [0] forever set [FPS v] to ((1) / ((timer) - (previous time))) set [previous time v] to (timer) end
| In this method, it is also possible to use the Days Since 2000 block in place of the timer. If this is done, make sure to multiply the days value by 86400 to convert it to seconds. |
Delta Time
Delta time can be used to make animations run consistently in real-time. Consider a project made for 30 FPS that is then run at 60 FPS: without any compensation the project runs twice as fast.
The following example calculates delta time and uses it in two motion blocks. As delta time is measured in seconds, the motion is now given in "units per second".
when green flag clicked set [last time v] to (days since 2000) forever set [delta time v] to (((days since 2000) - (last time)) * (86400)) // 86400 seconds in a day set [FPS v] to (round((1) / (delta time))) set [last time v] to (days since 2000) end when green flag clicked forever move ((210) * (delta time)) steps // moves at a speed of 210 steps per second turn cw ((180) * (delta time)) degrees // rotates at 180 degrees per second end