+1 vote

I want to create a method that calls exactly 30 times each second, how can i do it?

asked Apr 12, 2017 in Engine
edited May 10, 2017

I guess you only want a certain update speed for a method and not for the entire game (as your title suggests). I am no math hero, so correct me if anything is incorrect.

(1) Custom timer:

``````var time_passed = 0
var calls_per_sec = 30
var time_for_one_call= 1 / calls_per_second

func _process (delta):

time_passed += delta

if time_passed >= time_for_one_call:
call_my_func()
time_passed -= time_for_one_call
``````

delta is the time which is passed from the last frame to the current frame, it varies depending on the workload. On a game, which runs at constant 60 fps, the delta is around ~0.017 seconds (17ms). Now, when you need 30 calls pers second, then 1 call needs 1 sec / 30 calls = ~ 0.03 seconds (33ms). Therefore you ask when are 0.03s passed? If so, call my function.

(2) Another approach may be Coroutines. But I don't see a way to effectively use them in this case. There is no simple way like Unity:

``````yield return new WaitForSeconds();
``````
answered Apr 12, 2017 by (119 points)
selected May 11, 2017

Looks good to me. Though I wonder if they want 30 times consecutively every second, or have it run at 30FPS.

``````var time = 0

func _fixed_process(delta):
time += delta

if(time > 1.0):
time -= 1.0
for i in range(30): # 30 consecutive calls every second
#myfunc()
``````
+1 vote

We might have better or more specific solutions for what you are trying to solve if we get more details.

Other than that, you can actually just use Timer node : http://docs.godotengine.org/en/stable/classes/class_timer.html

answered Apr 12, 2017 by (216 points)

good idea :)