How do I activate an animation with a press of a button?

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

I’m new to Godot, and I wanted to learn how to use the AnimationPlayer node. I created an animation and could make it play automatically via scripting, but whenever I try to code it so it starts when I press a button, nothing happens. Please help.

extends Area2D

func _ready():
    if Input.is_action_pressed("swing"):
        get_node("anim").play("attack")

Note: I couldn’t get indents to show so I just used underscores.

You format the code by putting four spaces or by clicking the “Code Sample” button at the top of the input window. I’ll edit your post for you.

kidscancode | 2019-12-30 17:51

:bust_in_silhouette: Reply From: kidscancode

The problem here is that you put that code in _ready(). That means it runs only once, at the time you start the project. After that, you’re never checking for the key press.

If you want to check for the key being pressed, you should do that in _input(), which is called whenever there’s an input event:

extends Area2D

func _input(event):
    if event.is_action_pressed("swing"):
        get_node("anim").play("attack")

I suggest reading the following tutorial, as it explains how to properly handle inputs in a variety of cases:
Input examples — Godot Engine (latest) documentation in English

Thank you very much!

CreamyMemeys | 2019-12-30 18:43