0 votes

im very new to godot and its programing is hard for me im trying to make a 2d platformer game but the melee animation wont work when i press the attack button the melee animation just does the first frame and then goes to the idle or run animation please help me i dont understand it

here is my player script:

extends KinematicBody2D

const UP = Vector2(0,-1)
const gravity = 20
const max_fall_speed = 200 
const max_speed = 100
const jump_force = 350
const accel = 10

var motion = Vector2()
var facing_right = true
var attacking = false

func _ready():
    pass

func _physics_process(delta):

    motion.y += gravity
    if motion.y > max_fall_speed:
        motion.y = max_fall_speed

    if facing_right == true:
        $player_sprite.scale.x = 1
    else:
        $player_sprite.scale.x = -1

    motion.x = clamp(motion.x, -max_speed, max_speed)

    if Input.is_action_pressed("right"):
        motion.x += accel
        facing_right = true
        $AnimationPlayer.play("run")
    elif Input.is_action_pressed("left"):
        motion.x -= accel
        facing_right = false
        $AnimationPlayer.play("run")
    else:
        motion.x = lerp(motion.x, 0, 0.2)
        $AnimationPlayer.play("idle")

    if Input.is_action_just_pressed("attack"):
        attacking = true
    else:
        attacking = false

    if is_on_floor():
        if Input.is_action_just_pressed("jump"):
            motion.y = -jump_force

    if Input.is_action_just_released("jump") && motion.y < 0:
        motion.y = 0

    if !is_on_floor():
        if motion.y < 0:
            $AnimationPlayer.play("jump")
        elif motion.y > 0:
            $AnimationPlayer.play("fall")

    motion = move_and_slide(motion,UP)


func _process(delta):
    if attacking == true:
        $AnimationPlayer.play("attack_1")

func _on_sword_hit_area_entered(area):
    if area.is_in_group("hurtbox"):
        area.take_damage()
in Engine by (12 points)
edited by

1 Answer

0 votes

play() will restart the animation, and the logic is going to do this every frame. You need to check if the animation is currently playing before calling play() again, otherwise it will keep jumping to time 0.

For example:

if Input.is_action_pressed("right"):
    motion.x += accel
    facing_right = true

    if($AnimationPlayer.current_animation != "run"):
            $AnimationPlayer.play("run")

https://docs.godotengine.org/en/stable/classes/class_animationplayer.html?highlight=animationplayer

by (5,192 points)
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.
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 webmaster@godotengine.org with your username.