Animation getting cut off

Godot Version

4.2.1.stable

Question

I’ve added a gunshot animation in each direction, but I am having 2 problems. One is that the animation is cut off unless the input key is held. The other is that the animation will loop if the input key is held. Any help is appreciated :slight_smile:

extends CharacterBody2D

@export var speed = 150
@onready var anim = $player_sprite
@onready var gunshot = $gunshot_sound

var direction = “down”
var is_shooting: bool = false
var last_anim_direction: String = “down”

func get_input():
var input_direction = Input.get_vector(“move_left”, “move_right”, “move_up”, “move_down”)
velocity = input_direction * speed

if Input.is_action_pressed("shoot"):
	anim.play("shoot_" + last_anim_direction)
	is_shooting = true
	await anim.animation_finished
if Input.is_action_just_released("shoot"):
	is_shooting = false

func update_animation():
if is_shooting: return

var is_moving = velocity.length_squared() > 0
if is_moving:
	if velocity.x < 0: direction = "left"
	elif velocity.x > 0: direction = "right"
	elif velocity.y > 0: direction = "down"
	elif velocity.y < 0: direction = "up"

	anim.play("walk_" + direction)

else:
	anim.play("idle_" + direction)
	last_anim_direction = direction

func update_sound_fx():
if is_shooting:
gunshot.play()
else:
gunshot.stop()

func _physics_process(_delta):
get_input()
move_and_slide()
update_animation()
update_sound_fx()

You set is_shooting to false as soon as the key gets released – and then update_animation will either play the “idle” or “walk” animation instead.

So this should work:

if Input.is_action_just_pressed("shoot"):
	anim.play("shoot_" + last_anim_direction)
	is_shooting = true
elif Input.is_action_just_released("shoot"):
	await anim.animation_finished
	is_shooting = false

Note that I changed is_action_pressed into is_action_just_pressed here, which may or may not be what you want (depending on if you want it to be possible to change the shooting direction mid-animation). I also turned the second if condition into an elif since there’s no way both conditions will be true at the same time.

With is_action_just_pressed that won’t be an issue.