My 2D Top Down Player Code

Godot Version

3.5

Question

i have this code, the animation work fine, but the attack animation play at the top, right, left, and down only if i was moving, if i was standing, the attack animation play on the left and right only.

Code:

extends KinematicBody2D

export var speed : float = 5000
var move_Direction = Vector2.ZERO
onready var animationTree = $AnimationTree
onready var animationState = animationTree.get("parameters/playback")
onready var sprite = $Sprite
var is_attacking = false

func _ready():
	animationTree.active = true

func _physics_process(delta):
	process_input()
	update_sprite_scale()

	if is_attacking:
		animationState.travel("attack")
	else:
		if move_Direction != Vector2.ZERO:
			animationTree.set("parameters/idle/blend_position", move_Direction) # idle
			animationTree.set("parameters/walk/blend_position", move_Direction) # walk
			animationState.travel("walk")
		else:
			animationState.travel("idle")

	move_and_slide(move_Direction * speed * delta)

func process_input():
	move_Direction.x = Input.get_action_strength("move_right") - Input.get_action_strength("move_left")
	move_Direction.y = Input.get_action_strength("move_down") - Input.get_action_strength("move_up")

	
	move_Direction = move_Direction.normalized()

	if Input.is_action_just_pressed("attack"):
		attack()

func update_sprite_scale():
	if Input.is_action_pressed("move_left"):
		sprite.scale.x = -1
	elif Input.is_action_pressed("move_right"):
		sprite.scale.x = 1

func attack():
	if not is_attacking:
		print("Player attacked!")
		is_attacking = true
		animationTree.set("parameters/attack/blend_position", move_Direction) # attack
		animationState.travel("attack")

		
		yield(get_tree().create_timer(0.4), "timeout")
		is_attacking = false
		animationState.travel("idle")

You need to change the blend_position of the attack animation after process_input() like you do with the other blend_positions or it will set to move_Direction value (0, 0 if you didn’t move) before attacking.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.