Skip to content

Commit 660c2ae

Browse files
committed
Add CharacterAnimationPlayerBehavior
Similar to CharacterSpriteBehavior, this behavior node can control an AnimationPlayer to play idle, walk and run animations depending on the velocity of a CharacterBody2D. Resolve #1225
1 parent c2272b7 commit 660c2ae

2 files changed

Lines changed: 70 additions & 0 deletions

File tree

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# SPDX-FileCopyrightText: The Threadbare Authors
2+
# SPDX-License-Identifier: MPL-2.0
3+
@tool
4+
class_name CharacterAnimationPlayerBehavior
5+
extends Node2D
6+
## @experimental
7+
##
8+
## Play animations in [member animation_player] according
9+
## to the velocity of [member character].
10+
## [br][br]
11+
## For creating simple characters, consider using [CharacterSpriteBehavior] instead.
12+
13+
## The [member CharacterBody2D.velocity] is used to change the [member animation_player].
14+
## [br][br]
15+
## [b]Note:[/b] If the grandparent node is a CharacterBody2D and this isn't set,
16+
## the grandparent node will be automatically assigned to this variable.
17+
@export var character: CharacterBody2D
18+
19+
## The controlled animation player.
20+
## [br][br]
21+
## [b]Note:[/b] If the parent node is an AnimationPlayer and this isn't set,
22+
## the parent node will be automatically assigned to this variable.
23+
@export var animation_player: AnimationPlayer:
24+
set = _set_animation_player
25+
26+
var _is_character_running: bool = false
27+
28+
29+
func _enter_tree() -> void:
30+
if not animation_player and get_parent() is AnimationPlayer:
31+
animation_player = get_parent()
32+
if not character and get_parent() and get_parent().get_parent() is CharacterBody2D:
33+
character = get_parent().get_parent()
34+
35+
36+
func _set_animation_player(new_animation_player: AnimationPlayer) -> void:
37+
animation_player = new_animation_player
38+
update_configuration_warnings()
39+
40+
41+
func _get_configuration_warnings() -> PackedStringArray:
42+
var warnings: PackedStringArray
43+
if animation_player is not AnimationPlayer:
44+
warnings.append("Animation Player must be set.")
45+
return warnings
46+
47+
48+
func _ready() -> void:
49+
if Engine.is_editor_hint():
50+
set_process(false)
51+
return
52+
53+
54+
func _process(_delta: float) -> void:
55+
if not character:
56+
return
57+
58+
if character.velocity.is_zero_approx():
59+
animation_player.play(&"idle")
60+
else:
61+
if _is_character_running:
62+
animation_player.play(&"run")
63+
else:
64+
animation_player.play(&"walk")
65+
66+
67+
## You can connect this callback to a [member InputWalkBehavior.running_changed] signal.
68+
func on_running_changed(is_running: bool) -> void:
69+
_is_character_running = is_running
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
uid://b3hx1n2yl88qr

0 commit comments

Comments
 (0)