how to have idle animation resume after my initiated animation?

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

extends KinematicBody2D

func _input(event):
if Input.is_action_pressed(“pickup”):
get_node(“Sprite”).play(“pet”)
else:
get_node(“Sprite”).play(“idle”)

Here is the code I have for my kinematic body “cat”. Ideally I want to able to press my “pickup” hotkey and have it play the “pet” animation and then resume back to the idle animation which is playing by default. I also want to be able to just tap the button instead of having to hold it down. I tried “Is_just_pressed” but it didn’t work. It is an animated Sprite node and what I have no lets me hold down the spacebar to play the animation then resumes back to idle after I let go, but I just want to tap. Thanks in advance for help.

also I realized I pasted the code incorrectly so the formatting looks bad. I am very sorry. I’m new to this

snoot | 2022-11-14 23:51

:bust_in_silhouette: Reply From: DDoop

There’s a control flow bug. Right now what’s happening is other input events (even things like mouse movement) are triggering your else control block. That immediately causes the idle animation to play. The function _input(event) gets called a lot. I think you’ll need to add an is_petting bool to the script, which gets turned to true when the specific action is performed, instead of that action firing a call to $Sprite.play().

You can also add a setter to the bool (var is_petting := false setget _on_is_petting_set) after the variable declaration (), then define the function:

func _on_is_petting_set(value):
    is_petting = value
    if is_petting:
        $Sprite.play("pet")

Note that to get the advantage of the setter I think you have to explicitly say self.is_petting = true not just is_petting = true inside your _input(event) if true conditional.

(this last part is just based on my best guess of how AnimatedSprite works)
I honestly haven’t worked with animations much yet, so if you end up with a Sprite object that performs the pet animation successfully and then stops animating, you might need to explicitly connect the Sprite’s animation_finished signal to a function that calls $Sprite.play('idle').

This is probably also simple to do functionally without an internal variable but this is just the first strategy that came to my head!

DDoop | 2022-11-15 00:08