+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 by PugMasterPug (110 points)
edited May 10, 2017 by PugMasterPug

3 Answers

+3 votes
Best answer

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 sparks (119 points)
selected May 11, 2017 by PugMasterPug

Thanks, it is really helpfull.

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 Omicron (216 points)

good idea :)

0 votes

When designing a game, could be better to make time-based things depending on FPS rather than seconds (if the game is a network based one, more methods of approximation will be needed).

Games will not run on real time systems not even on reliable computers like consoles of old where you got everything at the same speed.

You can relax the "exactly" part and go for something "nearly" instead.
Timer node may work fine at 0.03 seconds which is close to your needs, if after 1000 seconds you notice a discrepancy, it can be fixed by delaying or accelerating the timer a bit, once.

answered Apr 13, 2017 by eons (7,618 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.