7 - Getting Game FPS

We'll be getting the game's frame rate (and changing the text's color).

Setting Up

Add a text object, add a text property, add an always sensor and a python controller, connect them, create a text file and connect them. Yes those bricks belong to the text object.

The code

To get the game framerate we should importing the game engine's logic function Range.logic.getAverageFrameRate() whose return type is a float. And then the code looks like this.

import Range
cont = Range.logic.getCurrentController()
own = cont.owner

FPS = Range.logic.getAverageFrameRate()

Here we've defined FPS as that function. Now to get the fps and put it on the text, the code looks like this.

import Range
cont = Range.logic.getCurrentController()
own = cont.owner

FPS = Range.logic.getAverageFrameRate()
own["Text"] = str(FPS)

Now run the game. If you see our text object is not getting the framerate but stays at 0.0, the reason is: Getting a game's frame is happening everyframe, and since our always logic brick is triggered once, it stays at zero. So go ahead and turn on true level triggering. Now it should work.

Don't worry if you have a lenghty going numbers like this.

Long ass numbers

There's an in-built python function called substring which is used to show a part of the string. On the line own["Text"] = str(FPS) put [:5]. The code looks like this.

import Range
cont = Range.logic.getCurrentController()
own = cont.owner

FPS = Range.logic.getAverageFrameRate()
own["Text"] = str(FPS)[:5]

This means the text object only display 5 characters. Now let's change the color of the text using the function color, which belongs to the class KX_GameObject. Our text object belongs to the class KX_FontObject which is a subclass of KX_GameObject.

The code looks like this.

a = 1
if FPS <= 60.1:
    own.color = 0,1,0,a
elif FPS <= 30:
    own.color = 1,1,0,a
elif FPS <= 20:
    own.color = 1,0,0,a
else:
    own.color = 0,0,1,a

What is actually happening here? Well, we are making our text object to turn green when the framerate is at or below 60. Turn yellow when the framerate is at or below 30 and turn red when the framerate is at or below 20. If its not anything specified turn blue.

color accepts 4 arguments which are red, green, blue and alpha. Values range from 0 and 1. a means alpha channel, I'll leave alpha as 1.

If you still don't understand you can play with the Blender's built-in color picker.

Blender's built-in color picker

Back to our stuff, the full code looks like this.

import Range
cont = Range.logic.getCurrentController()
own = cont.owner

FPS = Range.logic.getAverageFrameRate()

own["Text"] = str(FPS)[:5]

a = 1

if FPS <= 60.1:
    own.color = 0,1,0,a
elif FPS <= 30:
    own.color = 1,1,0,a
elif FPS <= 20:
    own.color = 1,0,0,a
else:
    own.color = 0,0,1,a

Download the project file. l7-python.blend