0 votes

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.

asked Dec 30, 2019 in Engine by CreamyMemeys (15 points)
edited Dec 30, 2019 by kidscancode

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.

1 Answer

+1 vote
Best answer

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:
https://docs.godotengine.org/en/latest/tutorials/inputs/input_examples.html

answered Dec 30, 2019 by kidscancode (17,714 points)
selected Dec 30, 2019 by CreamyMemeys

Thank you very much!

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 How to use this Q&A? before posting your first questions.