Use timer for camera shake (flip flop)

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

Hello everyone!

I’m quite new to Godot and GDScript in particular. Have worked with UE4 and Blueprints a lot, so some of my analogues would use the terminology from BPs.

I want to make camera shake by changine the v_offset parameter (just for testing purposes). Basically I need to flip-flop it’s values every time the timer ends. But what I could get is only one value: the timer shoots every two seconds, but I can’t figure out how to return the value after that.

onready var shakeTimer = get_node("Timer")
onready var camera = get_node("Head/Camera")
onready var headBob : bool = true

func _shakeCamera():
    if headBob = true :
        print ("true")
        camera.v_offset -= 0.5

func _on_Timer_timeout():
    headBob = false
    if headBob == false :
        print ("false")
        camera.v_offset += 0.5
        headBob = true
        _shakeCamera()

The result is that the engine executes both values at the same time (timer is set for 2 seconds) : true and false. And in theory I need it to work consequently: true > 2 seconds > false. I know that it may sound and look weird. Probably, I can’t get some very obvious and basic programming idea.

I’d be glad if you help.

sorry if I misunderstood. You want to shake the camera for every 2 seconds? Maybe you can add yield(get_tree().create_timer(0.2), "timeout")
before headBob = true (you can change 0.2 to the time you want)
example:

func _on_Timer_timeout():
    headBob = false
    if headBob == false :
        print ("false")
        camera.offset_v += 0.5
        yield(get_tree().create_timer(0.2), "timeout")
        headBob = true
        _shakeCamera()

it will make the command delay for 0.2 seconds before the offset turning back.

Or if you want to make like true → 2 seconds → false → 2 seconds → true and the rest, just

func _shakeCamera():
    if headBob == true :
        print ("true")
        camera.offset_v -= 0.5
    else:
        print("false")
        camera.offset_v += 0.5
    

func _on_Timer_timeout():
    headBob = !headBob
    _shakeCamera()

DeerForMera | 2022-02-08 06:12

Oh, the “yield” statement is exactly what I was looking for!
Thanks!

Rocotos | 2022-02-08 09:42

:bust_in_silhouette: Reply From: rossunger

You might want to use an animation player and make an animation. There’s an option to play animations flip flop style. If there’s not a specific reason you’re creating the animation in code, the animation player is great for this simple kinda thing.