Aries Fung
Aries Fung

Reputation: 11

GDScript: How to play an animation while key is preessed?

I am very new to coding and I'm still trying different languages out, I started off with GameMaker Studio and changed to Godot due to its compatibility with Mac I might as well learn something newer since GameMaker has been out for quite some time.

I want to create a RPG game and apply animation to each direction the character moves but the animation only plays after the key is pressed AND lifted. This means that while my key is pressed, the animation stops, and the animation only plays while my character is standing still, which is the complete opposite of what I want. The script looked really straight forward, but doesn't seem to be working.

I would tag this as the GDScript language instead of Python, but I guess I'm not reputable enough to make a new tag, so I tagged it under python because it is the most similar. #variables extends KinematicBody2D

const spd = 100

var direction = Vector2()

var anim_player = null

func _ready():
    set_fixed_process(true)
    anim_player = get_node("move/ani_move")

#movement and sprite change
func _fixed_process(delta):
    if (Input.is_action_pressed("ui_left")) :
         direction.x = -spd
         anim_player.play("ani_player_left")
    elif (Input.is_action_pressed("ui_right")):
        direction.x =  spd
        anim_player.play("ani_player_right")
    else:
         direction.x = 0

    if (Input.is_action_pressed("ui_up")) :
         direction.y = -spd
         anim_player.play("ani_player_up")
    elif (Input.is_action_pressed("ui_down")):
         direction.y =  (spd)
         anim_player.play("ani_player_down")
    else:
         direction.y = 0

    if (Input.is_action_pressed("ui_right")) and (Input.is_action_pressed("ui_left")):
        direction.x = 0
    if (Input.is_action_pressed("ui_up")) and (Input.is_action_pressed("ui_down")) :
        direction.y = 0

    # move
    var motion = direction * delta
    move(motion)

Upvotes: 1

Views: 3001

Answers (2)

Evander
Evander

Reputation: 76

You need to know if the animation has changed

First you need to put these variables in your code:

var currentAnim = ""
var newAnim = ""

And then you add this in your _fixed process:

if newAnim != anim:
    anim = newAnim
    anim_player.play(newAnim)

To change the animation you use:

newAnim = "new animation here"

Upvotes: 0

Ray
Ray

Reputation: 8844

As you check the input in _fixed_process, you call anim_player.play() several times a frame, which always seems to restart the animation, and thus, keeps the very first frame of the animation visible all the time.

As soon as you release the key, anim_player.play() stops resetting the animation back to start, and it can actually proceed to play the following frames.

A simple straight-forward solution would be to remember the last animation you played, and only call play() as soon as it changes.

Upvotes: 1

Related Questions