
Godot 2d Animation
- 386 installs
- 454 repo stars
- Updated July 28, 2026
- thedivergentai/gd-agentic-skills
godot-2d-animation is an agent skill that teaches Godot 4.5+ patterns for AnimatedSprite2D, skeletal cutout rigs, and frame-perfect 2D animation for developers building character motion and VFX timing.
About
godot-2d-animation is a GD-Agentic-Skills module targeting Godot 4.5+ with expert patterns for frame-based and skeletal 2D animation. The skill bundles 10 GDScript helper scripts—including animation_sync.gd, procedural_squash_stretch.gd, skeleton_2d_rig_helper.gd, and animation_tree_step.gd—for frame-perfect SFX/VFX triggers, squash-and-stretch deformation, FABRIK/CCDIK bone rigs, and AnimationTree state-machine travel. It documents critical pitfalls such as using animation_looped instead of animation_finished for loops, calling advance(0) after play() to avoid one-frame glitches, and set_frame_and_progress() for mid-animation skin swaps. A decision tree maps scenarios to AnimatedSprite2D, AnimationPlayer, AnimationTree, Tween, or MultiMeshInstance2D plus shader swarms. Developers reach for godot-2d-animation when implementing sprite frame animations, cutout Bone2D hierarchies, procedural squash/stretch on landing, or GPU-optimized swarm animation in Godot 2D projects.
- godot-2d-animation
Godot 2d Animation by the numbers
- 386 all-time installs (skills.sh)
- +20 installs in the week ending Jul 27, 2026 (Skillselion tracking)
- Ranked #1,091 of 4,347 Backend & APIs skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/thedivergentai/gd-agentic-skills --skill godot-2d-animationAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 386 |
|---|---|
| repo stars | ★ 454 |
| Last updated | July 28, 2026 |
| Repository | thedivergentai/gd-agentic-skills ↗ |
How do you implement frame-perfect 2D animation in Godot?
Use godot-2d-animation for development tasks
Who is it for?
Godot game developers implementing character sprites, cutout rigs, or animation state machines in 2D projects.
Skip if: Teams building 3D skeletal animation, UI-only apps, or games on engines other than Godot 4.5+.
When should I use this skill?
A developer asks about AnimatedSprite2D, SpriteFrames, Bone2D cutout rigs, animation_looped signals, or squash-and-stretch in Godot 2D.
What you get
GDScript animation controllers, Bone2D rig setup, and frame-sync patterns integrated into Godot 2D scenes.
- GDScript animation controllers
- Bone2D rig patterns
- frame-sync event maps
By the numbers
- Bundles 10 GDScript helper scripts for 2D animation patterns
- Targets Godot 4.5+ in the GD-Agentic-Skills library
Files
2D Animation
Expert-level guidance for frame-based and skeletal 2D animation in Godot.
NEVER Do
- NEVER use AnimatedTexture — This class is deprecated, highly inefficient in modern renderers, and may be removed in future Godot versions. Use AnimatedSprite2D or AnimationPlayer instead.
- NEVER allow Tweens to fight over the same property — If multiple Tweens animate the same property, the last one created forcibly takes priority. Always assign your Tween to a variable and call
kill()on the previous instance before creating a new one. - NEVER process kinematic movement outside the physics tick — If your AnimationPlayer moves a CharacterBody2D, ensure the AnimationPlayer's callback mode is set to Physics. Animating physics bodies during the Idle (render) frame breaks fixed timestep physics interpolation and causes stutter.
- NEVER use `animation_finished` for looping animations — The signal only fires on non-looping animations. Use
animation_loopedinstead for loop detection. - NEVER call `play()` and expect instant state changes — AnimatedSprite2D applies
play()on the next process frame. Calladvance(0)immediately afterplay()if you need synchronous property updates (e.g., when changing animation + flip_h simultaneously). - NEVER set `frame` directly when preserving animation progress — Setting
frameresetsframe_progressto 0.0. Useset_frame_and_progress(frame, progress)to maintain smooth transitions when swapping animations mid-frame. - NEVER forget to cache `@onready var anim_sprite` — The node lookup getter is surprisingly slow in hot paths like
_physics_process(). Always use@onready. - NEVER mix AnimationPlayer tracks with code-driven AnimatedSprite2D — Choose one animation authority per sprite. Mixing causes flickering and state conflicts.
- NEVER use paper-thin skeletons for deformation — 2D meshes require balanced vertex density. If your mesh deforms poorly, increase the vertex count near joints in the Mesh2D editor.
---
Available Scripts
MANDATORY: Read the appropriate script before implementing the corresponding pattern.
animation_sync.gd
Method track triggers for frame-perfect logic (SFX/VFX hitboxes), signal-driven async gameplay orchestration, and AnimationTree blend space management. Use when syncing gameplay events to animation frames.
animation_state_sync.gd
Frame-perfect state-driven animation with transition queueing - essential for responsive character animation.
shader_hook.gd
Animating ShaderMaterial uniforms via AnimationPlayer property tracks. Covers hit flash, dissolve effects, and instance uniforms for batched sprites. Use for visual feedback tied to animation states.
procedural_squash_stretch.gd
Dynamic physics-driven deformation. Provides lerp logic for smoothing out sudden impact squashes and directional stretches based on high-velocity movement.
skeleton_2d_rig_helper.gd
Programmatic rig management. Tuning FABRIK/CCDIK modification stacks and updating bone rest poses at runtime for procedural limb goal-reaching.
animation_tree_step.gd
Expert state machine control. Utilizes AnimationNodeStateMachinePlayback.travel() to leverage the engine's internal A* pathfinding for multi-state transitions.
one_frame_sync_fix.gd
Eliminates the "One-Frame Glitch" by using advance(0) to force the engine to apply animation poses immediately alongside property changes like flip_h.
gpu_mesh_optimizer.gd
Architectural pattern for bypassing GPU fill-rate bottlenecks. Demonstrates when to convert large sprites into specialized 2D meshes to avoid transparent pixel overhead.
multimesh_swarm_anim.gd
Optimization for thousands of entities. Offloads animation logic (sine waves, flight patterns) to the GPU vertex shader to eliminate CPU node processing.
tween_lifecycle_manager.gd
Safe and memory-efficient Tween orchestration. Handles interruption cleanup and property-fight prevention in fast-paced gameplay loops.
---
AnimatedSprite2D Signals (Expert Usage)
animation_looped vs animation_finished
extends CharacterBody2D
@onready var anim: AnimatedSprite2D = $AnimatedSprite2D
func _ready() -> void:
# ✅ Correct: Use animation_looped for repeating animations
anim.animation_looped.connect(_on_loop)
# ✅ Correct: Use animation_finished ONLY for one-shots
anim.animation_finished.connect(_on_finished)
anim.play("run") # Looping animation
func _on_loop() -> void:
# Fires every loop iteration
emit_particle_effect("dust")
func _on_finished() -> void:
# Only fires for non-looping animations
anim.play("idle")frame_changed for Event Triggering
# Frame-perfect event system (attacks, footsteps, etc.)
extends AnimatedSprite2D
signal attack_hit
signal footstep
# Define event frames per animation
const EVENT_FRAMES := {
"attack": {3: "attack_hit", 7: "attack_hit"},
"run": {2: "footstep", 5: "footstep"}
}
func _ready() -> void:
frame_changed.connect(_on_frame_changed)
func _on_frame_changed() -> void:
var events := EVENT_FRAMES.get(animation, {})
if frame in events:
emit_signal(events[frame])---
Advanced Pattern: Animation State Sync
Problem: play() Timing Glitch
When updating both animation and sprite properties (e.g., flip_h + animation change), play() doesn't apply until next frame, causing a 1-frame visual glitch.
# ❌ BAD: Glitches for 1 frame
func change_direction(dir: int) -> void:
anim.flip_h = (dir < 0)
anim.play("run") # Applied NEXT frame
# Result: 1 frame of wrong animation with correct flip
# ✅ GOOD: Force immediate sync
func change_direction(dir: int) -> void:
anim.flip_h = (dir < 0)
anim.play("run")
anim.advance(0) # Force immediate update---
set_frame_and_progress() for Smooth Transitions
Use when changing animations mid-animation without visual stutter:
# Example: Skin swapping without animation reset
func swap_skin(new_skin: String) -> void:
var current_frame := anim.frame
var current_progress := anim.frame_progress
# Load new SpriteFrames resource
anim.sprite_frames = load("res://skins/%s.tres" % new_skin)
# ✅ Preserve exact animation state
anim.play(anim.animation) # Re-apply animation
anim.set_frame_and_progress(current_frame, current_progress)
# Result: Seamless skin swap mid-animation---
Expert Decision Tree: Choosing the Right Animation Tool
| Scenario | Recommended Node | Expert Insight |
|---|---|---|
| Isolated, pure frame-by-frame spritesheets | AnimatedSprite2D | Simple and effective, but cannot animate non-visual properties, manipulate transforms, or trigger external methods. |
| Cutout animations, non-visual sync, audio/particles | AnimationPlayer | Required when manipulating transforms of many child sprites, driving 2D mesh deformations, or syncing methods/particles to visual frames. |
| Complex state machines, blending, locomotion | AnimationTree | Essential for blending movement directions. Does not hold animations itself; it's a logic graph driving an underlying AnimationPlayer. |
| Procedural, dynamic, fire-and-forget UI/fx | Tween | Target values calculated at runtime. Far more lightweight than AnimationPlayer; designed to be created and discarded via script. |
| Swarms of thousands of entities (bats, fish) | MultiMeshInstance2D + Shader | Bypasses the node system entirely. Calculate sine waves/movement on the GPU vertex shader to avoid massive CPU bottlenecks. |
---
Expert Pattern: Procedural Squash & Stretch
# Physics-driven squash/stretch for game feel
extends CharacterBody2D
@onready var sprite: Sprite2D = $Sprite2D
var _base_scale := Vector2.ONE
func _physics_process(delta: float) -> void:
var prev_velocity := velocity
move_and_slide()
# Squash on landing
if not is_on_floor() and is_on_floor():
var impact_strength := clamp(abs(prev_velocity.y) / 800.0, 0.0, 1.0)
_squash_and_stretch(Vector2(1.0 + impact_strength * 0.3, 1.0 - impact_strength * 0.3))
# Stretch during jump
elif velocity.y < -200:
sprite.scale = _base_scale.lerp(Vector2(0.9, 1.1), delta * 5.0)
else:
sprite.scale = sprite.scale.lerp(_base_scale, delta * 10.0)
func _squash_and_stretch(target_scale: Vector2) -> void:
var tween := create_tween().set_trans(Tween.TRANS_BACK).set_ease(Tween.EASE_OUT)
tween.tween_property(sprite, "scale", target_scale, 0.08)
tween.tween_property(sprite, "scale", _base_scale, 0.12)---
Cutout Animation (Bone2D Skeleton)
For complex skeletal animation, use Bone2D instead of manual Sprite2D parenting:
Skeleton Setup
Player (Node2D)
└─ Skeleton2D
├─ Bone2D (Root - Torso)
│ ├─ Sprite2D (Body)
│ └─ Bone2D (Head)
│ └─ Sprite2D (Head)
├─ Bone2D (ArmLeft)
│ └─ Sprite2D (Arm)
└─ Bone2D (ArmRight)
└─ Sprite2D (Arm)AnimationPlayer Tracks
# Key bone rotations in AnimationPlayer
# Tracks:
# - "Skeleton2D/Bone2D:rotation"
# - "Skeleton2D/Bone2D/Bone2D2:rotation" (head)
# - "Skeleton2D/Bone2D3:rotation" (arm left)Why Bone2D over manual parenting?
- Forward Kinematics (FK) and Inverse Kinematics (IK) support
- Easier to rig and weight paint
- Better integration with animation retargeting
---
Performance: SpriteFrames Optimization
# ✅ GOOD: Share SpriteFrames resource across instances
const SHARED_FRAMES := preload("res://characters/player_frames.tres")
func _ready() -> void:
anim_sprite.sprite_frames = SHARED_FRAMES
# All player instances share same resource in memory
# ❌ BAD: Each instance loads separately
func _ready() -> void:
anim_sprite.sprite_frames = load("res://characters/player_frames.tres")
# Duplicates resource in memory per instance---
Edge Case: Pixel Art Centering
# Pixel art textures can appear blurry when centered between pixels
# Solution 1: Disable centering
anim_sprite.centered = false
anim_sprite.offset = Vector2.ZERO
# Solution 2: Enable global pixel snapping (Project Settings)
# rendering/2d/snap/snap_2d_vertices_to_pixel = true
# rendering/2d/snap/snap_2d_transforms_to_pixel = trueSpriteFrames Texture Filtering
# Problem: SpriteFrames uses bilinear filtering (blurry for pixel art)
# Solution: In Import tab for each texture:
# - Filter: Nearest (for pixel art)
# - Mipmaps: Off (prevents blending at distance)
# Or set globally in Project Settings:
# rendering/textures/canvas_textures/default_texture_filter = Nearest---
Expert Techniques & Optimizations
1. Hybrid Cutout and Cel Animation
Do not limit yourself to just one style. Use AnimationPlayer to rig a 2D skeleton and animate the bones (Cutout animation), while simultaneously keyframing the texture or frame properties of specific child sprites. This allows highly efficient transform-based animation for the body, while selectively swapping hand shapes or facial expressions using traditional hand-drawn cel animation.
2. Optimizing GPU Fill Rate with 2D Meshes
Sprites with large transparent areas (like tree leaves) waste GPU fill rate. Convert a Sprite2D into a MeshInstance2D in Godot. This generates a 2D polygon that tightly hugs the opaque pixels, bypassing transparent areas. While this slightly increases vertex processing time, it massively improves GPU fill rate on complex 2D scenes.
3. Safe Tween Interruption and Looping
Game states change rapidly. Ensure Tweens are properly cleaned up before starting new ones to avoid memory leaks and conflicting animations.
extends Node2D
var _tween: Tween
func animate_damage_flash() -> void:
# Anti-pattern prevention: Always kill the existing tween before overwriting it.
if _tween:
_tween.kill()
_tween = create_tween()
# Chain tweeners and use loops for rapid, predictable animation
_tween.set_loops(3)
_tween.tween_property($Sprite2D, "modulate", Color.RED, 0.1).set_trans(Tween.TRANS_SINE)
_tween.tween_property($Sprite2D, "modulate", Color.WHITE, 0.1).set_trans(Tween.TRANS_SINE)4. Advanced State Machine Travel via AnimationTree
When using an AnimationNodeStateMachine within an AnimationTree, you do not directly "play" animations. You command the state machine to compute the shortest path (using A*) to a new state.
extends CharacterBody2D
@onready var animation_tree: AnimationTree = $AnimationTree
# Retrieve the playback object from the AnimationTree properties
@onready var state_machine: AnimationNodeStateMachinePlayback = animation_tree.get("parameters/playback")
func _ready() -> void:
# The state machine must be started before traveling
state_machine.start("idle")
func _physics_process(delta: float) -> void:
if velocity.length() > 0:
# Travel to the run state. Internal A* will seamlessly play intermediate transitions.
state_machine.travel("run")
else:
state_machine.travel("idle")---
Expert Pattern: Animation-Frame-Data-Extractor
To extract custom per-frame metadata (e.g., spawn offsets, hitbox sizes), use an AnimationPlayer in conjunction with AnimatedSprite2D. SpriteFrames is strictly a visual container; AnimationPlayer allows you to decouple visual data from logical metadata using Value Tracks or Call Method Tracks.
class_name AnimationDataExtractor extends CharacterBody2D
# 1. Define the metadata property (Value Track target)
@export var current_spawn_offset: Vector2 = Vector2.ZERO:
set(value):
current_spawn_offset = value
_update_spawn_point()
@onready var anim_player: AnimationPlayer = $AnimationPlayer
@onready var spawn_marker: Marker2D = $SpawnMarker
func _ready() -> void:
# Playing via AnimationPlayer updates 'current_spawn_offset' on keyed frames
anim_player.play("attack_shoot")
func _update_spawn_point() -> void:
spawn_marker.position = current_spawn_offset
# 2. Call Method Track Implementation
# Use this to pass complex arguments directly to a function on a specific frame
func spawn_projectile(damage: int, specific_offset: Vector2) -> void:
var projectile = PROJECTILE_SCENE.instantiate()
projectile.damage = damage
projectile.position = global_position + specific_offset
get_parent().add_child(projectile)---
Expert Pattern: Skeletal-IK-2D (Procedural Foot Placement)
For procedural limb positioning (e.g., planting feet on slopes), use Godot's built-in 2D skeletal modification system. The SkeletonModification2DTwoBoneIK is the elite choice for limbs as it is more lightweight than full FABRIK solvers.
Setup
1. Add a SkeletonModificationStack2D to your Skeleton2D. 2. Add a SkeletonModification2DTwoBoneIK to the stack. 3. Assign the target bones (e.g., UpperLeg and LowerLeg). 4. Point the target_nodepath to a Marker2D (IK Target).
class_name ProceduralWalker2D extends Node2D
@onready var skeleton: Skeleton2D = $Skeleton2D
@onready var ik_target_left_foot: Marker2D = $IKTargets/LeftFootTarget
@onready var floor_raycast: RayCast2D = $RayCasts/LeftFootRay
func _ready() -> void:
# Ensure modification stack is enabled
var mod_stack: SkeletonModificationStack2D = skeleton.get_modification_stack()
if mod_stack:
mod_stack.enabled = true
mod_stack.enable_all_modifications(true)
func _physics_process(_delta: float) -> void:
floor_raycast.force_raycast_update()
if floor_raycast.is_colliding():
# Move IK target to the exact collision point
ik_target_left_foot.global_position = floor_raycast.get_collision_point()
else:
# Fallback to resting position
ik_target_left_foot.position = Vector2(0, 50)---
Expert Pattern: Sprite-Sheet-Memory-Manager
Dynamically load and unload high-resolution textures to optimize VRAM usage. Leverage ResourceLoader for asynchronous loading and RefCounted for automatic memory purging.
class_name SpriteSheetMemoryManager extends Node
@onready var animated_sprite: AnimatedSprite2D = $AnimatedSprite2D
var _pending_path: String = ""
var _target_anim: StringName = &"heavy_attack"
func load_high_res_anim(path: String) -> void:
_pending_path = path
# 1. Start background loading to prevent frame stutter
ResourceLoader.load_threaded_request(_pending_path)
set_process(true)
func _process(_delta: float) -> void:
# 2. Check loading status
var status = ResourceLoader.load_threaded_get_status(_pending_path)
if status == ResourceLoader.THREAD_LOAD_LOADED:
var tex: Texture2D = ResourceLoader.load_threaded_get(_pending_path)
_apply_to_frames(tex)
set_process(false)
func _apply_to_frames(tex: Texture2D) -> void:
var frames: SpriteFrames = animated_sprite.sprite_frames
if not frames.has_animation(_target_anim):
frames.add_animation(_target_anim)
# 3. Inject frame dynamically
frames.add_frame(_target_anim, tex)
animated_sprite.play(_target_anim)
func unload_high_res_anim() -> void:
var frames: SpriteFrames = animated_sprite.sprite_frames
if frames.has_animation(_target_anim):
# 4. Breaking the reference to the Texture2D frees it from RAM
frames.clear(_target_anim)Reference
- Master Skill: godot-master
# skills/2d-animation/scripts/animation_state_sync.gd
extends Node
## Animation State Synchronization Expert Pattern
## Frame-perfect state-driven animation with transition queueing.
class_name AnimationStateSync
signal animation_state_changed(from_state: String, to_state: String)
@export var anim_sprite: AnimatedSprite2D
@export var transition_queue_enabled := true
var current_state := ""
var _queued_state := ""
var _transition_frame := -1
func _ready() -> void:
if not anim_sprite:
push_error("AnimationStateSync: anim_sprite not assigned!")
return
# Connect to frame changes for precise transitions
anim_sprite.animation_finished.connect(_on_animation_finished)
anim_sprite.frame_changed.connect(_on_frame_changed)
func transition_to(state: String, immediate := false) -> void:
if state == current_state and anim_sprite.is_playing():
return
if not anim_sprite.sprite_frames.has_animation(state):
push_warning("Animation state '%s' does not exist" % state)
return
if immediate or current_state.is_empty():
_execute_transition(state)
elif transition_queue_enabled:
_queued_state = state
else:
_execute_transition(state)
func _execute_transition(state: String) -> void:
var old_state := current_state
current_state = state
anim_sprite.play(state)
animation_state_changed.emit(old_state, state)
_queued_state = ""
func _on_animation_finished() -> void:
if not _queued_state.is_empty():
_execute_transition(_queued_state)
func _on_frame_changed() -> void:
# For frame-perfect events on specific frames
if _transition_frame >= 0 and anim_sprite.frame == _transition_frame:
if not _queued_state.is_empty():
_execute_transition(_queued_state)
_transition_frame = -1
func set_transition_frame(frame: int) -> void:
_transition_frame = frame
## EXPERT USAGE:
## var anim_sync := AnimationStateSync.new()
## anim_sync.anim_sprite = $AnimatedSprite2D
##
## # State-driven animation
## if is_on_floor():
## anim_sync.transition_to("idle" if velocity.x == 0 else "run")
## else:
## anim_sync.transition_to("jump" if velocity.y < 0 else "fall")
# skills/2d-animation/code/animation_sync.gd
extends CharacterBody2D
## 2D Animation Sync Expert Pattern
## This script demonstrates:
## 1. Method track triggers for frame-perfect logic (SFX/VFX)
## 2. Signal-driven async gameplay orchestration
## 3. AnimationTree blend space management
@onready var anim_player: AnimationPlayer = $AnimationPlayer
@onready var anim_tree: AnimationTree = $AnimationTree
@onready var playback: AnimationNodeStateMachinePlayback = anim_tree["parameters/playback"]
signal attack_landed(target: Node2D)
signal footstep_triggered(position: Vector2)
# --- 1. Method Track Triggers ---
# These functions should be called via 'Method Track' keyframes in AnimationPlayer
# Use 'emit_footstep' at the exact frame the foot touches the ground.
func emit_footstep() -> void:
footstep_triggered.emit(global_position)
# Expert Tip: Use AudioServer or a dedicated SoundPool for performance
# print_debug("Footstep at ", Time.get_ticks_msec())
func emit_attack_hitbox() -> void:
# Logic to enable/disable hitboxes based on animation frames
# This is more precise than timers or polling
pass
# --- 2. Signal-Driven Async Logic ---
# Patterns for connecting animation 'finished' signals to gameplay events.
func perform_action_sequence() -> void:
# Syncing gameplay logic with animation completion using await
playback.travel("SpecialAction")
# Wait for the animation to finish OR for a specific frame event
await anim_player.animation_finished
# Trigger secondary effects once animation is officially done
_on_action_completed()
func _on_action_completed() -> void:
# Resume movement or trigger next state
pass
# --- 3. Blend Space Smoothing ---
# Expert handling of AnimationTree parameters for fluid transitions.
func update_movement_animation(velocity_vector: Vector2) -> void:
# Use 'lerp' or 'move_toward' on the blend space position
# if you want custom logic beyond the AnimationTree's built-in damping.
var target_blend: Vector2 = velocity_vector.normalized()
# parameters/IdleRun/blend_position is a common path for 2D BlendSpaces
anim_tree.set("parameters/IdleRun/blend_position", target_blend)
# Logic for character flipping based on blend direction
if target_blend.x != 0:
$Sprite2D.flip_h = target_blend.x < 0
# AnimationTree A* Travel Pattern
extends CharacterBody2D
## Using AnimationNodeStateMachinePlayback allows for intelligent pathfinding
## through your animation states (A* algorithm), unlike AnimationPlayer.play().
@onready var animation_tree: AnimationTree = $AnimationTree
@onready var playback: AnimationNodeStateMachinePlayback = animation_tree.get("parameters/playback")
func _ready() -> void:
# Mandatory initialization
animation_tree.active = true
playback.start("idle")
func _physics_process(_delta: float) -> void:
var move_input := Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down")
if move_input.length() > 0:
# travel() will play the "start_running" transition first if it exists
playback.travel("run")
else:
# travel() will play "stop_running" or "wind_down" automatically
playback.travel("idle")
func trigger_one_shot(state_name: String) -> void:
# traveling to a one-shot state is cleaner than forcing an animation
if playback.get_current_node() != state_name:
playback.travel(state_name)
# GPU Fill Rate Optimization via MeshInstance2D
extends Node2D
## Drawing large transparent areas is expensive for GPUs (Fill Rate bottleneck).
## Use MeshInstance2D to create a tight polygon around your sprite.
func convert_sprite_to_optimized_mesh(sprite: Sprite2D) -> MeshInstance2D:
# While normally done in the Editor (Sprite2D > "Convert to MeshInstance2D"),
# this conceptual script highlights the logic.
var mesh_node = MeshInstance2D.new()
mesh_node.texture = sprite.texture
# Architecture Tip: For thousands of trees/grass, MeshInstance2D is mandatory
# because it bypasses the transparent alpha blending overhead for empty space.
# In your master scene, prefer MeshInstance2D over Sprite2D for static
# environmental animations (like swaying trees) to protect your GPU budget.
return mesh_node
# MultiMesh Swarm Animation Shader Hook
extends MultiMeshInstance2D
## For swarms (birds, fish, projectiles), Node2D overhead is the bottleneck.
## Use a Shader to animate thousands of instances on the GPU.
func _ready() -> void:
var mat = material as ShaderMaterial
# Pass the start time to the shader to sync animations
mat.set_shader_parameter("start_time", Time.get_ticks_msec() / 1000.0)
# Example Shader Snippet (to be put in .gdshader):
# void vertex() {
# float phase = TIME * speed + (float(INSTANCE_ID) * 0.5);
# VERTEX.y += sin(phase) * amplitude; // Procedural GPU animation
# }
# Expert One-Frame Glitch Sync Fix
extends Node2D
## When playing an animation and changing a property (like flip_h) in the same frame,
## play() is queued and doesn't apply until the next frame, causing a glitch.
## Use advance(0) to force an immediate application.
@onready var anim_player: AnimationPlayer = $AnimationPlayer
@onready var sprite: Sprite2D = $Sprite2D
func change_animation_and_flip(anim_name: String, should_flip: bool) -> void:
sprite.flip_h = should_flip
anim_player.play(anim_name)
# CRITICAL: Forces the AnimationPlayer to apply the first frame of the NEW animation
# using the NEW flip_h state IMMEDIATELY. Eliminates the 1-frame "ghosting" pose.
anim_player.advance(0)
func force_sync_method_tracks() -> void:
# advance(0) also triggers method tracks at the very start of the animation
# ensuring SFX or logic triggers don't wait for the next engine tick.
anim_player.play("attack")
anim_player.advance(0)
# Procedural Squash and Stretch for Godot 2D
extends Sprite2D
@export var squash_stretch_rate := 10.0
@export var impact_threshold := 500.0
var _base_scale: Vector2
var _target_scale: Vector2
func _ready() -> void:
_base_scale = scale
_target_scale = scale
func _process(delta: float) -> void:
# Continuous smoothing toward target or base
scale = scale.lerp(_target_scale, squash_stretch_rate * delta)
_target_scale = _target_scale.lerp(_base_scale, squash_stretch_rate * delta)
## Calculate deformation based on velocity.
## Call this in _physics_process before move_and_slide for stretching,
## or immediately after a collision impact for squashing.
func apply_velocity_deformation(velocity: Vector2, max_velocity: float = 1000.0) -> void:
var speed_ratio := clamp(velocity.length() / max_velocity, 0.0, 1.0)
# Stretch along the move axis, squash the perpendicular
_target_scale = _base_scale * Vector2(1.0 - speed_ratio * 0.2, 1.0 + speed_ratio * 0.4)
# Orient the sprite to face the movement for directional stretch
rotation = velocity.angle() + PI/2
func apply_impact_squash(impact_velocity: float) -> void:
if abs(impact_velocity) < impact_threshold:
return
var strength := clamp(abs(impact_velocity) / 2000.0, 0.0, 0.5)
# Sudden squash: wide and short
scale = _base_scale * Vector2(1.0 + strength, 1.0 - strength)
_target_scale = _base_scale
# skills/2d-animation/code/shader_hook.gd
extends Sprite2D
## Shader Parameter Hooks Expert Pattern
## Demonstrates animating ShaderMaterial uniforms directly via AnimationPlayer.
# 1. Ensure the Sprite2D has a ShaderMaterial assigned.
# 2. In AnimationPlayer, add a track of type 'Property Track'.
# 3. Path: "material:shader_parameter/line_thickness" (as an example).
@onready var anim_player: AnimationPlayer = $AnimationPlayer
## Example uniform names:
## 'line_thickness' for outline shaders
## 'dissolve_value' for teleport/death effects
## 'hit_flash' for damage feedback
func trigger_damage_flash() -> void:
# Programmatic trigger if needed, but best practice is to have
# a dedicated 'Damage' animation that handles this visually.
anim_player.play("HitFlash")
func trigger_teleport_out() -> void:
# Using await to ensure gameplay waits for the visual effect
anim_player.play("Dissolve")
await anim_player.animation_finished
# Logic to remove character or move position
# queue_free() # or hide()
## EXPERT NOTE:
## If you need to animate parameters on many instances (like grass blowing),
## use 'Instance Uniforms' in Godot 4.0+ to avoid creating unique material
## resources for every sprite, which saves significant memory/draw calls.
## Path for animation: "instance_shader_parameters/parameter_name"
# Expert 2D IK and Skeleton Setup
extends Skeleton2D
## Note: In Godot 4.x, 2D IK is primarily handled via the "SkeletonModificationStack2D".
## This script demonstrates programmatic setup and modification of bone constraints.
@onready var modification_stack: SkeletonModificationStack2D = get_modification_stack()
func _ready() -> void:
# Ensure the stack is enabled
modification_stack.enabled = true
setup_ik_constraint()
func setup_ik_constraint() -> void:
# Logic to find or create a FABRIK or CCDIK modification at runtime
if modification_stack.get_modification_count() == 0:
# Programmatic adding of IK is advanced; usually done via editor
# but properties can be tuned here.
push_warning("Ensure a modification stack is added in the editor for this script to tune it.")
return
var mod = modification_stack.get_modification(0)
if mod is SkeletonModification2DFABRIK:
mod.target_nodepath = get_parent().get_path_to($"../TargetMarker")
mod.chain_length = 3 # Number of bones to affect upward from the tip
print("IK Target successfully synced to TargetMarker")
func update_bone_rest_pose(bone_name: String, new_transform: Transform2D) -> void:
var bone = find_child(bone_name) as Bone2D
if bone:
bone.rest = new_transform
# Mandatory for the skeleton to recognize the change
bone.apply_rest()
# Safe Tween Lifecycle Manager
extends Node
## Tweens in Godot 4 are lightweight, but fighting and leaks are common.
## This pattern ensures interruptions are handled gracefully.
var _active_tween: Tween
func play_safe_ui_pop(target_node: Control) -> void:
# MANDATORY: Kill previous tween before overwriting to prevent logic fights
if _active_tween:
_active_tween.kill()
_active_tween = create_tween().set_parallel(true).set_trans(Tween.TRANS_BACK)
# Chain animations safely
_active_tween.tween_property(target_node, "scale", Vector2.ONE, 0.3).from(Vector2.ZERO)
_active_tween.tween_property(target_node, "modulate:a", 1.0, 0.2).from(0.0)
# Cleanup reference when done
_active_tween.finished.connect(func(): _active_tween = null)
func interrupt_all_tweens() -> void:
if _active_tween:
_active_tween.kill()
Related skills
How it compares
Pick godot-2d-animation over generic Godot scripting skills when the task is specifically 2D sprite timing, cutout rigs, or AnimationTree locomotion blending.
FAQ
Which Godot version does godot-2d-animation target?
godot-2d-animation targets Godot 4.5+ within the GD-Agentic-Skills library. Patterns use AnimatedSprite2D, Bone2D, AnimationTree, and GDScript APIs current to modern Godot 2D animation workflows.
What scripts does godot-2d-animation include?
godot-2d-animation ships 10 GDScript helper scripts including animation_sync.gd, procedural_squash_stretch.gd, skeleton_2d_rig_helper.gd, animation_tree_step.gd, and tween_lifecycle_manager.gd. Agents read the matching script before implementing each pattern.