Play animation with code: Static function "play()" not found in base "GDScriptNativeClass"

Godot Version

4, 2d

im tryna play an animation , not an animatedsprite2d btw, but it wont play

heres the code, if you need the node order please ask

extends CharacterBody2D

@onready var animation = $AnimationPlayer
const SPEED = 300.0
const JUMP_VELOCITY = -400.0

var gravity = ProjectSettings.get_setting(“physics/2d/default_gravity”)

func _physics_process(delta):
# Add gravity if the character is not on the floor.
if not is_on_floor():
velocity.y += gravity * delta

if Input.is_action_just_pressed("jump") and is_on_floor():
	velocity.y = JUMP_VELOCITY


var direction = Input.get_axis("ui_left", "ui_right")
if direction:
	velocity.x = direction * SPEED
else:
	velocity.x = move_toward(velocity.x, 0, SPEED)


if Input.is_action_just_pressed("ui_left"):
		Animation.play("leftarm")


move_and_slide()

GDScript is case-sensitive so Animation is different with animation.

animation is a variable you just defined and Animation is a Godot class which has no static function named play. You need call animation.play("leftarm") instead.

2 Likes

thanks, now it runs, but i want it to loop as long as it is pressed, how do you do that?

on the animationplayer mnext to the time buton the is a loop icon and you have to prese that

Instead of is_action_just_pressed use is_action_pressed.

but i want it to loop as long as it is pressed, how do you do that?

Well, one way to see the way to program this, is by stopping the animation when “ui_left” is released, and replay it when the action has been pressed.

The code then should be:

extends CharacterBody2D


const SPEED = 300.0
const JUMP_VELOCITY = -400.0


var gravity = ProjectSettings.get_setting(“physics/2d/default_gravity”)


@onready var animation = $AnimationPlayer


func _physics_process(delta):
    # Add gravity if the character is not on the floor.
    if not is_on_floor():
    velocity.y += gravity * delta
    if Input.is_action_just_pressed("jump") and is_on_floor():
        velocity.y = JUMP_VELOCITY


    var direction = Input.get_axis("ui_left", "ui_right")
    if direction:
        velocity.x = direction * SPEED
    else:
	    velocity.x = move_toward(velocity.x, 0, SPEED)


    if Input.is_action_just_pressed("ui_left"):
        """
        If no animation was played before => plays "left_arm"
        If "left_arm" was paused => resumes from the last position (cf docs)
        No need to check if the assigned_animation is the same since "left_arm" is the only animation played
        """
        animation.play("leftarm")
    elif Input.is_action_just_released("ui_left"):
        animation.pause()


move_and_slide()

(cf pause, play methods and assigned_animation property, AnimationPlayer — Godot Engine (stable) documentation in English)