Why my function is running only once in the physics_process?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By psych6vzz

So i have a piece of code running fine on my physics process, but when i try to make it a function, it runs only once even if i’m calling it on the physics process.

Here’s the code that works fine:

curve_weight = 3
speed_output = curve.interpolate(speed_input)
speed_input += curve_weight * delta if moving else -curve_weight * delta
speed_input = clamp(speed_input, 0, 1)

Here’s the function of this same code:

func _get_curspeed_output(delta : float, is_mov: bool, spd_in : float, spd_out : float, cur_weight : float, cur : Curve) -> float:
spd_out = cur.interpolate(spd_in)
spd_in += cur_weight * delta if is_mov else -cur_weight * delta
spd_in = clamp(spd_in, 0, 1)
return spd_out

And the function when i call it in the physics process:

curve_output = _get_curspeed_output(delta, moving, speed_input, speed_output, curve_weight, curve)

When debugging the spd_in, it should return the increment from 0 to 1 based on the weight passed thru the curve i’m using, however it only executes the += once when i’m moving and the += negative value once when i’m not (It keeps stuck between 0 and 0.05).
Am i executing it wrong? I couldn’t find nothing on it on the documentation or the internet

:bust_in_silhouette: Reply From: timothybrentwood

You want something like this:

var spd_in = 0

func _physics_process(delta):
    curve_output = _get_curspeed_output(delta, moving, speed_output, curve_weight, curve)

func _get_curspeed_output(delta : float, is_mov: bool, spd_out : float, cur_weight : float, cur : Curve) -> float:
    spd_out = cur.interpolate(spd_in)
    spd_in += cur_weight * delta if is_mov else -cur_weight * delta
    spd_in = clamp(spd_in, 0, 1)
    return spd_out

The way your code is structured spd_in gets updated inside of _get_curspeed_output() then nothing happens to that new value so that new updated value goes away once it leaves the scope of the function after executing return spd_out. Then _get_curspeed_output() gets called again with the same original value of spd_in the next frame.