+1 vote

extends KinematicBody2D

func input(event):
if Input.is
actionpressed("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 "Isjustpressed" 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.

in Engine by (13 points)

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

1 Answer

0 votes

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').

by (735 points)

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

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 Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.