Search code examples
mobilegame-physicsframe-rategodotgdscript

Godot Objects are moving at varying speeds


I am new to Godot and have been working on a little project to help me learn. In this project, I have a wheel that turns when the user touches the screen and a ball that comes from the center of the screen outward. When I run the project, the ball will sometimes go unusually faster for a second or two and the wheel will spin almost instantly. I assume this has something to do with the framerate of the game but how do I make sure that this does not happen when I publish my game to the app store?
(All code is in GDScript)

Code for moving ball(ball.gd):

var movev = Vector2(0,0)
func _process(delta):
    position += movev

Code for rotating wheel(Wheel.gd):

var goal = 0
func _process(delta):
    if goal > rotation:
        rotation += deg2rad(1)

Code for when screen is clicked(World.gd):

onready var Wheel = get_node("Wheel/Center")
func _on_Button_button_down():
    Wheel.goal += deg2rad(45)

Here is a video I made showing what I am talking about: Video Link

What is causing this behavior and how do I stabilize it?


Solution

  • The parameter delta tells you the time elapsed. You need to multiply your velocity by it.


    Consider, for example:

    var movev = Vector2(0,0)
    func _process(delta):
        position += movev
    

    Here you have a velocity movev, and a position position. Velocity is delta position over delta time. Thus, position and velocity are different units, you should not add them.

    If you have delta position over delta time, you need to multiply by delta time to get delta position. And that delta position you can add to your position.

    See also: instantaneous velocity.


    From Godot documentation:

    the delta parameter contains the time elapsed in seconds as a floating-point number since the previous call to _process()

    Thus, you code should be:

    var movev = Vector2(0,0)
    func _process(delta):
        position += movev * delta
    

    Similarly for angular velocity:

    var goal = 0
    func _process(delta):
        if goal > rotation:
            rotation += deg2rad(1) * delta
    

    Note: you may find that your velocity is too slow or too fast after this change. Remember the units. The parameter delta, as the documentation says, is in seconds. Thus, you should express your angular velocities in angle per second and your linear velocity in position displacement per second. I also remind you that the magnitud of the velocity velocity is speed, which is distance of time.